package com.bonus.bracelet.service.impl;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.bonus.bracelet.mapper.ConsControlMapper;
import com.bonus.bracelet.service.IConsControlService;
import com.bonus.common.core.constant.BusinessConstants;
import com.bonus.common.core.constant.HttpStatus;
import com.bonus.common.core.constant.SecurityConstants;
import com.bonus.common.core.domain.R;
import com.bonus.common.core.utils.DateTimeHelper;
import com.bonus.common.core.utils.HaversineUtil;
import com.bonus.common.core.utils.TimeValidator;
import com.bonus.common.core.utils.encryption.Sm4Utils;
import com.bonus.common.core.web.domain.AjaxResult;
import com.bonus.common.entity.app.vo.DevInfoVo;
import com.bonus.common.entity.app.vo.DevWarnVo;
import com.bonus.common.entity.app.vo.JdConfigVo;
import com.bonus.common.entity.bracelet.BraceletParamsDto;
import com.bonus.common.core.utils.BuildTreeUtil;
import com.bonus.common.entity.bracelet.vo.*;
import com.bonus.common.security.utils.ValidatorsUtils;
import com.bonus.system.api.RemoteFileService;
import com.bonus.system.api.RemoteTcpService;
import com.bonus.system.api.domain.SysFile;
import com.bonus.system.api.domain.SysTcpMessage;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @className:ConsControlServiceImpl
 * @author:cwchen
 * @date:2024-08-08-9:56
 * @version:1.0
 * @description:施工管控
 */
@Service(value = "IConsControlService")
@Slf4j
public class ConsControlServiceImpl implements IConsControlService {

    @Resource(name = "ConsControlMapper")
    private ConsControlMapper mapper;

    @Resource
    private RemoteFileService remoteFileService;

    @Resource(name = "ValidatorsUtils")
    private ValidatorsUtils validatorsUtils;

    @Resource
    private RemoteTcpService remoteTcpService;

    @Override
    public AjaxResult getBallDeviceLists(BraceletParamsDto dto) {
        JSONArray resultTree = new JSONArray();
        JSONArray dataTree = new JSONArray();
        try {
            List<BallTreeVo> list = new ArrayList<>();
            list = mapper.getBallDeviceLists(dto);
            for (BallTreeVo vo : list) {
                //忽略工程数据
                if (Objects.equals(vo.getParentId(), BusinessConstants.PARENT_ID)) {
                    continue;
                }
                String[] valArr = vo.getLabel().split("-");
                if (StringUtils.isNotEmpty(valArr[1])) {
                    vo.setLabel(valArr[0] + "-" + Sm4Utils.decode(valArr[1]));
                }
            }
            //构建球机树
            resultTree = BuildTreeUtil.listInfoToTree(JSONArray.parseArray(JSON.toJSONString(list)), "id", "parentId", "children");
            if (CollectionUtils.isNotEmpty(resultTree)) {
                for (int i = 0; i < resultTree.size(); i++) {
                    JSONObject jsonObject = resultTree.getJSONObject(i);
                    JSONArray children = jsonObject.getJSONArray("children");
                    if (CollectionUtils.isNotEmpty(children)) {
                        dataTree.add(jsonObject);
                    }
                }
            }
        } catch (Exception e) {
            log.error(e.toString(), e);
        }
        return AjaxResult.success(dataTree);
    }

    @Override
    public AjaxResult getBallWarnLists(BraceletParamsDto dto) {
        List<List<WarnInfoVo>> dataList = new ArrayList<>();
        try {
            // 设备类型设置为球机
            dto.setDevType(BusinessConstants.BALL);
            List<WarnInfoVo> warnInfoVoList = mapper.getBallWarnLists(dto);
            if (CollectionUtils.isNotEmpty(warnInfoVoList)) {
                for (int i = 0; i < warnInfoVoList.size(); i++) {
                    WarnInfoVo warnInfoVo = warnInfoVoList.get(i);
                    if (StringUtils.isEmpty(warnInfoVo.getBase64Url())) {
                        warnInfoVo.setBase64Url("66c68c712350293fa1d6b197");
                    }
                    // 前三张违章照片加载图片，其余调用加载
                    if (i < 3) {
                        String imgBase64 = getImgBase64(warnInfoVo.getBase64Url());
                        warnInfoVo.setBase64Url(imgBase64);
                        warnInfoVo.setIsLoad(true);
                    }
                }
                dataList = groupList(warnInfoVoList);
            }
        } catch (Exception e) {
            log.error(e.toString(), e);
        }
        return AjaxResult.success(dataList);
    }

    private static final Integer MAX_NUMBER = 3;

    /**
     * 计算切分次数
     */
    private static Integer countStep(Integer size) {
        return (size + MAX_NUMBER - 1) / MAX_NUMBER;
    }

    /**
     * 切割数组
     *
     * @param list
     * @return List<List < WarnInfoVo>>
     * @author cwchen
     * @date 2024/8/22 13:31
     */
    public List<List<WarnInfoVo>> groupList(List<WarnInfoVo> list) {
        List<List<WarnInfoVo>> dataList = new ArrayList<>();
        int limit = countStep(list.size());
        dataList = Stream.iterate(0, n -> n + 1).limit(limit).parallel().map(a -> list.stream().skip(a * MAX_NUMBER).limit(MAX_NUMBER).parallel().collect(Collectors.toList())).collect(Collectors.toList());
        return dataList;
    }

    /**
     * 获取违章识别图片的base64
     *
     * @param base64Url
     * @return String
     * @author cwchen
     * @date 2024/8/8 18:36
     */
    public String getImgBase64(String base64Url) {
        try {
            R<SysFile> result = remoteFileService.getImgBase64(base64Url, SecurityConstants.INNER);
            if (result != null && result.getCode() == HttpStatus.SUCCESS && result.getData() != null) {
                String jsonString = JSON.toJSONString(result.getData());
                JSONObject item = JSON.parseObject(jsonString);
                String base64 = item.getString("url");
                return base64;
            }
        } catch (Exception e) {
            log.error(e.toString(), e);
        }
        return null;
    }

    @Override
    public PageInfo<WarnInfoVo> getWarnLists(BraceletParamsDto dto) {
        List<WarnInfoVo> warnInfoVoList = new ArrayList<>();
        try {
            // 设备类型设置为球机
            dto.setDevType(BusinessConstants.BALL);
            warnInfoVoList = mapper.getWarnLists(dto);
        } catch (Exception e) {
            log.error(e.toString(), e);
        }
        PageInfo<WarnInfoVo> pageInfo = new PageInfo<>(warnInfoVoList);
        return pageInfo;
    }

    @Override
    public AjaxResult getPersonsTree(BraceletParamsDto dto) {
        JSONArray resultTree = new JSONArray();
        try {
            List<PersonTreeVo> list = new ArrayList<>();
            List<Long> proIds = new ArrayList<>();
            List<Long> gtIds = new ArrayList<>();
            List<Long> teamIds = new ArrayList<>();
            list = mapper.getPersonsTree(dto);
            list.forEach(item->{
                if (Objects.equals(item.getLevel(), BusinessConstants.LEVEL)) {
                    String[] valArr = item.getLabel().split("-");
                    if (StringUtils.isNotEmpty(valArr[1])) {
                        item.setLabel(valArr[0] + "-" + Sm4Utils.decode(valArr[1]));
                    }
                    // 判断施工人员是否预警
                    Integer isWarn = beyondTheScopeOfConstruction(dto, item.getDevId(), item.getGtId());
                    if(!Objects.equals(isWarn,BusinessConstants.NO_WARN)){
                        proIds.add(item.getProId());
                        gtIds.add(item.getGtId());
                        teamIds.add(item.getTeamId());
                    }
                    item.setIsWarn(isWarn);
                }
            });
            Set<Long> proIdsSet = new HashSet<>(proIds);
            Set<Long> gtIdsSet = new HashSet<>(gtIds);
            Set<Long> teamIdsSet = new HashSet<>(teamIds);
            for (PersonTreeVo vo : list) {
                //忽略工程数据、杆塔、班组数据 1.工程 2.杆塔 3.班组 4.班组成员/临时人员
                if (!Objects.equals(vo.getLevel(), BusinessConstants.LEVEL)) {
                    if(Objects.equals(vo.getLevel(),BusinessConstants.LEVEL1)){
                        // 工程
                        vo.setIsWarn(warnValue(vo.getId(),proIdsSet));
                    }else if(Objects.equals(vo.getLevel(),BusinessConstants.LEVEL2)){
                        // 杆塔
                        vo.setIsWarn(warnValue(vo.getId(),gtIdsSet));
                    }else if(Objects.equals(vo.getLevel(),BusinessConstants.LEVEL3)){
                        // 班组
                        vo.setIsWarn(warnValue(vo.getId(),teamIdsSet));
                    }
                }
            }
            //构建人员树
            resultTree = BuildTreeUtil.listInfoToTree(JSONArray.parseArray(JSON.toJSONString(list)), "id", "parentId", "children");
        } catch (Exception e) {
            log.error(e.toString(), e);
        }
        return AjaxResult.success(resultTree);
    }

    public Integer warnValue(String value,Set<Long> setList){
        Long id = Long.parseLong(value.replace("tower-", "").replace("team-", ""));
        if(CollectionUtils.isEmpty(setList)){
            return 0;
        }else{
            if (setList.contains(id)) {
                return 1;
            }
        }
        return 0;
    }

    @Override
    public AjaxResult getWorkInfo(BraceletParamsDto dto) {
        Map<String, Object> mapData = new HashMap<>();
        try {
            // 获取施工班组、施工人数（包含班组人员和临时人员））、安全帽绑定信息
            List<Integer> workTeamList = mapper.getWorkNum(dto);
            List<Map<String, Object>> safetyHatLists = mapper.getSafetyHatInfo(dto);
            if (CollectionUtils.isNotEmpty(safetyHatLists)) {
                for (Map<String, Object> map : safetyHatLists) {
                    if (map.get("phone") != null) {
                        map.put("phone", Sm4Utils.decode(String.valueOf(map.get("phone"))));
                    }
                }
            }
            mapData.put("workTeamNum", workTeamList.get(0));
            mapData.put("workPersonNum", workTeamList.get(1));
            mapData.put("safetyHatList", safetyHatLists);
        } catch (Exception e) {
            log.error(e.toString(), e);
        }
        return AjaxResult.success(mapData);
    }

    /**
     * 班组人员是否超过施工范围
     *
     * @param devId
     * @param gtId
     * @return Integer
     * @author cwchen
     * @date 2024/8/23 13:42
     */
    public Integer beyondTheScopeOfConstruction(BraceletParamsDto dto, Long devId, Long gtId) {
        // 获取杆塔信息、施工距离、绑定手环的班组施工人员/临时人员 位置信息
        dto.setId(gtId);
        PersonControlVo.TowerInfo towerInfo = mapper.getTowerInfo(dto);
        String distance = mapper.getDistance();
        if (StringUtils.isNotBlank(distance)) {
            towerInfo.setDistance(Double.parseDouble(distance));
        }
        PersonControlVo.WorkPersonInfo workPersonInfo = new PersonControlVo.WorkPersonInfo();
        List<PersonControlVo.BraceletInfo> braceletInfoList = mapper.getShDeviceInfo(devId);
        workPersonInfo = getLatAndLon(braceletInfoList, workPersonInfo);
        Integer isAbnormal = isAbnormal(workPersonInfo, towerInfo);
        return isAbnormal;
    }

    @Override
    public AjaxResult getPersonsInfo(BraceletParamsDto dto) {
        Map<String, Object> mapData = new HashMap<>();
        try {
            // 获取杆塔信息、施工距离、绑定手环的班组施工人员/临时人员 位置信息
            PersonControlVo.TowerInfo towerInfo = mapper.getTowerInfo(dto);
            String distance = mapper.getDistance();
            if (StringUtils.isNotBlank(distance)) {
                towerInfo.setDistance(Double.parseDouble(distance));
            }
            List<PersonControlVo.WorkPersonInfo> personList = mapper.getWorkPersonInfo(dto);
            if (CollectionUtils.isNotEmpty(personList)) {
                for (PersonControlVo.WorkPersonInfo workPersonInfo : personList) {
                    if (StringUtils.isNotBlank(workPersonInfo.getPhone())) {
                        workPersonInfo.setPhone(Sm4Utils.decode(workPersonInfo.getPhone()));
                    }
                    // 获取已绑手环的定位信息
                    List<PersonControlVo.BraceletInfo> braceletInfoList = mapper.getShDeviceInfo(workPersonInfo.getDevId());
                    workPersonInfo = getLatAndLon(braceletInfoList, workPersonInfo);
                    // 验证施工人员是否超出施工范围
                    Integer isAbnormal = isAbnormal(workPersonInfo, towerInfo);
                    workPersonInfo.setIsWarn(isAbnormal);
                }
            }
            mapData.put("towerInfo", towerInfo);
            mapData.put("personList", personList);
        } catch (Exception e) {
            log.error(e.toString(), e);
        }
        return AjaxResult.success(mapData);
    }

    @Override
    public AjaxResult getTeamPersonByTower(BraceletParamsDto dto) {
        JSONArray resultTree = new JSONArray();
        try {
            List<TeamPeopleTreeVo> list = new ArrayList<>();
            list = mapper.getTeamPersonByTower(dto);
            for (TeamPeopleTreeVo vo : list) {
                //忽略工程数据
                if (Objects.equals(vo.getParentId(), BusinessConstants.PARENT_ID) || Objects.equals(vo.getId(), BusinessConstants.PARENT_ID)) {
                    continue;
                }
                String[] valArr = vo.getLabel().split("-");
                if (StringUtils.isNotEmpty(valArr[1])) {
                    vo.setLabel(valArr[0] + "-" + Sm4Utils.decode(valArr[1]));
                }
            }
            //构建班组人员树
            resultTree = BuildTreeUtil.listInfoToTree(JSONArray.parseArray(JSON.toJSONString(list)), "id", "parentId", "children");
        } catch (Exception e) {
            log.error(e.toString(), e);
        }
        return AjaxResult.success(resultTree);
    }

    @Override
    public AjaxResult spotCheck(BraceletParamsDto dto) {
        try {
            if (CollectionUtils.isEmpty(dto.getSpotCheckList())) {
                return AjaxResult.error("未选择班组人员，进行手环人脸验证");
            }
            for (BraceletParamsDto.SpotCheckInfo info : dto.getSpotCheckList()) {
                if (info.getUserId() == null) {
                    return AjaxResult.error("人员ID不能为空");
                }
                if (info.getUserType() == null) {
                    return AjaxResult.error("人员类型不能为空");
                }
                if (StringUtils.isBlank(info.getDevCode())) {
                    return AjaxResult.error("设备级联编码不能为空");
                }
                if (StringUtils.isBlank(info.getShCode())) {
                    return AjaxResult.error("手环编码不能为空");
                }
            }
            // 批量下发手环人脸验证指令-未对接
        } catch (Exception e) {
            log.error(e.toString(), e);
        }
        return AjaxResult.success("已下达手环人脸验证抽检指令");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult checkConfig(CheckConfigVo vo) {
        try {
            // 删除配置项
            mapper.delConfig();
            mapper.delConfigItems();
            if (Objects.equals(vo.getConfigType(), BusinessConstants.CONFIG_TYPE)) {
                if (StringUtils.isEmpty(vo.getTime())) {
                    return AjaxResult.error("固定时间不能为空");
                }
                // 固定时间验证
                String[] timeArr = vo.getTime().split(",");
                if (timeArr.length > 10) {
                    return AjaxResult.error("固定时间验证不能超过十个配置项");
                }
                for (String time : timeArr) {
                    if (!TimeValidator.isValidTime(time)) {
                        return AjaxResult.error("时间格式错误（HH:MM）");
                    }
                }
            } else if (Objects.equals(vo.getConfigType(), BusinessConstants.CONFIG_TYPE2)) {
                // 间隔时间验证
                if (!TimeValidator.isValidTime2(vo.getTime())) {
                    return AjaxResult.error("间隔时间应在1-10的正整数范围");
                }
            }
            // 添加配置项、配置项内容
            mapper.addConfig(vo);
            if (Objects.equals(vo.getConfigType(), BusinessConstants.CONFIG_TYPE)) {
                String[] timeArr = vo.getTime().split(",");
                for (String time : timeArr) {
                    mapper.addConfigItems(vo, time);
                }
            } else if (Objects.equals(vo.getConfigType(), BusinessConstants.CONFIG_TYPE2)) {
                mapper.addConfigItems(vo, vo.getTime());
            }

        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            log.error(e.toString(), e);
            return AjaxResult.error();
        }
        return AjaxResult.success();
    }

    @Override
    public AjaxResult getCheckConfig(BraceletParamsDto dto) {
        List<CheckConfigVo> list = new ArrayList<>();
        try {
            list = mapper.getCheckConfig(dto);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return AjaxResult.success(list);
    }

    @Override
    public AjaxResult getPersonDetail(BraceletParamsDto dto) {
        Map<String, Object> dataMap = new HashMap<>(16);
        try {
            // 获取人员基本信息
            PersonDetailVo vo = mapper.getPersonInfoData(dto);
            vo.setPhone(Sm4Utils.decode(vo.getPhone()));
            vo.setIdCard(Sm4Utils.decode(vo.getIdCard()));
            // 判断人员是否绑定了安全帽
            PersonDetailVo.SafetyHat safetyHat = mapper.getSafetyHat(dto);
            if (safetyHat != null) {
                vo.setHasSafetyHat(true);
                vo.setSafetyHat(safetyHat);
            }
            // 获取施工杆塔信息
            dto.setId(vo.getTowerId());
            PersonControlVo.TowerInfo towerInfo = mapper.getTowerInfo(dto);
            PersonControlVo.WorkPersonInfo workPersonInfo = new PersonControlVo.WorkPersonInfo();
            // 获取已绑手环的信息
            String distance = mapper.getDistance();
            if (StringUtils.isNotBlank(distance)) {
                towerInfo.setDistance(Double.parseDouble(distance));
            }
            List<PersonControlVo.BraceletInfo> braceletInfoList = mapper.getShDeviceInfo(vo.getBraceletId());
            workPersonInfo = getLatAndLon(braceletInfoList, workPersonInfo);
            // 设置绑定手环基本信息
            vo = setBraceletInfo(vo, braceletInfoList);
            // 验证施工人员是否超出施工范围/人脸是否验证
            Integer isAbnormal = isAbnormal(workPersonInfo, towerInfo);
            if (!Objects.equals(isAbnormal, BusinessConstants.NO_WARN) || !Objects.equals(vo.getFaceStatus(), BusinessConstants.PASS)) {
                vo.setWarnType("danger");
            }
            if (!Objects.equals(isAbnormal, BusinessConstants.NO_WARN) && Objects.equals(vo.getFaceStatus(), BusinessConstants.PASS)) {
                vo.setWarnName("离开工作区域");
                vo.getBracelet().setIsWarn(1);
            } else if (Objects.equals(isAbnormal, BusinessConstants.NO_WARN) && !Objects.equals(vo.getFaceStatus(), BusinessConstants.PASS)) {
                vo.setWarnName("人脸验证异常");
            } else if (!Objects.equals(isAbnormal, BusinessConstants.NO_WARN) && !Objects.equals(vo.getFaceStatus(), BusinessConstants.PASS)) {
                vo.setWarnName("离开工作区域/人脸验证异常");
                vo.getBracelet().setIsWarn(1);
            }
            // 获取手环的预警信息
            dto.setStartTime(DateTimeHelper.getNowDay());
            dto.setEndTime(DateTimeHelper.getNowDay());
            dto.setId(vo.getBraceletId());
            List<PersonDetailVo.WarnInfo> warnInfoList = mapper.getWarnInfo(dto);
            vo.setWarnInfoList(warnInfoList);
            dataMap.put("vo", vo);
        } catch (Exception e) {
            log.error(e.toString(), e);
        }
        return AjaxResult.success(dataMap);
    }

    @Override
    public AjaxResult getHistoryGj(BraceletParamsDto dto) {
        List<Map<String, Object>> list = new ArrayList<>();
        List<Map<String, Object>> dataList = new ArrayList<>();
        try {
            List<String> dataNameList = new ArrayList<>();
            dataNameList.add(BusinessConstants.LON);
            dataNameList.add(BusinessConstants.LAT);
            dto.setDataName(dataNameList);
            if (StringUtils.isEmpty(dto.getStartTime())) {
                dto.setStartTime(DateTimeHelper.getNowDay());
            }
            list = mapper.getHistoryGj(dto);
            for (Map<String, Object> map : list) {
                String value = (String) map.get("value");
                String[] valueArr = value.split(",");
                if (valueArr.length == 2 && StringUtils.isNotBlank(valueArr[0]) && StringUtils.isNotBlank(valueArr[1])) {
                    Map<String, Object> dataMap = new HashMap<>(2);
                    dataMap.put("lon", valueArr[0]);
                    dataMap.put("lat", valueArr[1]);
                    dataList.add(dataMap);
                }
            }
        } catch (Exception e) {
            log.error(e.toString(), e);
        }
        return AjaxResult.success(dataList);
    }

    @Override
    public AjaxResult getDzWarnList(BraceletParamsDto dto) {
        List<DevInfoVo> list = new ArrayList<>();
        try {
            dto.setDevType(BusinessConstants.DZYJ);
            list = mapper.getDzWarnList(dto);
            for (DevInfoVo vo : list) {
                vo.setLeaderPhone(Sm4Utils.decode(vo.getLeaderPhone()));
            }
        } catch (Exception e) {
            log.error(e.toString(), e);
        }
        return AjaxResult.success(list);
    }

    /**
     * 班组人员/临时人员 是否超出正常施工范围
     *
     * @param workPersonInfo
     * @param towerInfo
     * @return Integer
     * @author cwchen
     * @date 2024/8/9 15:56
     */
    public Integer isAbnormal(PersonControlVo.WorkPersonInfo workPersonInfo, PersonControlVo.TowerInfo towerInfo) {
        Integer isWarn = 0;
        if (StringUtils.isEmpty(towerInfo.getLon())
                || StringUtils.isEmpty(towerInfo.getLat())
                || StringUtils.isEmpty(workPersonInfo.getLon())
                || StringUtils.isEmpty(workPersonInfo.getLat())
        ) {
            return isWarn;
        }
        Double lat = Double.parseDouble(towerInfo.getLon());
        Double lon = Double.parseDouble(towerInfo.getLat());
        Double sgLat = Double.parseDouble(workPersonInfo.getLon());
        Double sgLon = Double.parseDouble(workPersonInfo.getLat());
        double len = HaversineUtil.vincentyDistance(sgLat, sgLon, lat, lon);
        if (len > towerInfo.getDistance()) {
            isWarn = 1;
        }
        return isWarn;
    }

    @Override
    public PageInfo<DevWarnVo> getJdWarnList(BraceletParamsDto dto) {
        List<DevWarnVo> list = new ArrayList<>();
        try {
            dto.setDevType(BusinessConstants.JD);
            // 告警数据默认展示当天，不需要加日期限制可去掉
            dto.setStartTime(DateTimeHelper.getNowDay());
            dto.setEndTime(DateTimeHelper.getNowDay());
            list = mapper.getJdWarnList(dto);
        } catch (Exception e) {
            log.error(e.toString(), e);
        }
        PageInfo<DevWarnVo> pageInfo = new PageInfo<>(list);
        return pageInfo;
    }

    @Override
    public AjaxResult getJdList(BraceletParamsDto dto) {
        List<DevInfoVo> list = new ArrayList<>();
        try {
            dto.setDevType(BusinessConstants.JD);
            list = mapper.getJdList(dto);
            for (DevInfoVo vo : list) {
                String electricQuantity = mapper.getElectricQuantity(vo.getDevId(), BusinessConstants.JD_DL);
                if (StringUtils.isNotBlank(electricQuantity) && isNumeric(electricQuantity)) {
                    vo.setElectricQuantity(electricQuantity);
                } else {
                    vo.setElectricQuantity("0");
                }
            }
        } catch (Exception e) {
            log.error(e.toString(), e);
        }
        return AjaxResult.success(list);
    }

    @Override
    public AjaxResult configJdDevice(JdConfigVo vo) {
        try {
            List<JdConfigVo.ConfigItems> configItems = vo.getConfigItems();
            if (CollectionUtils.isEmpty(configItems)) {
                return AjaxResult.error("配置项不能为空");
            }
            if (configItems.size() > 10) {
                return AjaxResult.error("设备配置项不能超过十个");
            }
            Set<JdConfigVo.ConfigItems> itemsHashSet = new HashSet<>(configItems);
            if (itemsHashSet.size() != configItems.size()) {
                return AjaxResult.error("配置项存在相同数据");
            }
            for (JdConfigVo.ConfigItems items : configItems) {
                String validResult = validatorsUtils.valid(items, JdConfigVo.ConfigItems.Query.class);
                if (StringUtils.isNotBlank(validResult)) {
                    return AjaxResult.error(validResult);
                }
            }
            SysTcpMessage sysTcpMessage = new SysTcpMessage();
            sysTcpMessage.setDevCode(vo.getDevCode());
            sysTcpMessage.setDistance(Float.parseFloat(configItems.get(0).getDistance()));
            R result = remoteTcpService.setMessage(sysTcpMessage, SecurityConstants.INNER);
            log.info("调用结果：code:{},msg:{}", result.getCode(),result.getMsg());
            if (result != null && result.getCode() == HttpStatus.SUCCESS && Objects.equals(result.getMsg(), BusinessConstants.SET_MSG)) {
                mapper.delJdConfig(vo);
                mapper.addJdConfigData(vo);
                return AjaxResult.success(result.getMsg());
            } else {
                return AjaxResult.error(result.getMsg());
            }
        } catch (Exception e) {
            log.error(e.toString(), e);
        }
        return AjaxResult.success();
    }

    @Override
    public AjaxResult getConfigJdDevice(BraceletParamsDto dto) {
        List<JdConfigVo.ConfigItems> list = new ArrayList<>();
        try {
            list = mapper.getConfigJdDevice(dto);
        } catch (Exception e) {
            log.error(e.toString(), e);
        }
        return AjaxResult.success(list);
    }

    @Override
    public AjaxResult getPhotosById(BraceletParamsDto dto) {
        List<String> base64List = new ArrayList<>();
        List<String> dataName = dto.getDataName();
        for (String filePath : dataName) {
            System.err.println(filePath);
            String imageBase64 = getImageBase64(filePath);
            base64List.add(imageBase64);
        }
        return AjaxResult.success(base64List);
    }

    /**
     * 获取文件
     *
     * @param filePath
     * @return String
     * @author cwchen
     * @date 2024/8/22 10:02
     */
    public String getImageBase64(String filePath) {
        R<SysFile> result = remoteFileService.getImgBase64(filePath, SecurityConstants.INNER);
        if (result != null && result.getCode() == HttpStatus.SUCCESS && result.getData() != null) {
            String jsonString = JSON.toJSONString(result.getData());
            JSONObject item = JSON.parseObject(jsonString);
            String base64 = item.getString("url");
            return base64;
        }
        return null;
    }

    /**
     * 赋值手环设备的经纬度
     *
     * @param braceletInfoList
     * @param workPersonInfo
     * @return PersonControlVo.WorkPersonInfo
     * @author cwchen
     * @date 2024/8/9 16:56
     */
    public PersonControlVo.WorkPersonInfo getLatAndLon(List<PersonControlVo.BraceletInfo> braceletInfoList, PersonControlVo.WorkPersonInfo workPersonInfo) {
        if (CollectionUtils.isEmpty(braceletInfoList)) {
            return workPersonInfo;
        }
        for (PersonControlVo.BraceletInfo braceletInfo : braceletInfoList) {
            if (Objects.equals(braceletInfo.getDataCode(), BusinessConstants.LON)) {
                workPersonInfo.setLon(braceletInfo.getDataVal());
            } else if (Objects.equals(braceletInfo.getDataCode(), BusinessConstants.LAT)) {
                workPersonInfo.setLat(braceletInfo.getDataVal());
            }
        }
        return workPersonInfo;
    }

    /**
     * 赋值手环信息
     *
     * @param vo
     * @param braceletInfoList
     * @return PersonDetailVo
     * @author cwchen
     * @date 2024/8/23 13:14
     */
    public PersonDetailVo setBraceletInfo(PersonDetailVo vo, List<PersonControlVo.BraceletInfo> braceletInfoList) {
        if (CollectionUtils.isEmpty(braceletInfoList)) {
            return vo;
        }
        PersonDetailVo.Bracelet bracelet = new PersonDetailVo.Bracelet();
        bracelet.setDevId(vo.getBraceletId());
        bracelet.setName(vo.getShCode());
        for (PersonControlVo.BraceletInfo braceletInfo : braceletInfoList) {
            if (Objects.equals(braceletInfo.getDataCode(), BusinessConstants.DL_CODE)) {
                Double value = handleElecValue(braceletInfo);
                bracelet.setElec(value);
            } else if (Objects.equals(braceletInfo.getDataCode(), BusinessConstants.XL_CODE)) {
                bracelet.setHeartRate(handleValue(braceletInfo));
            } else if (Objects.equals(braceletInfo.getDataCode(), BusinessConstants.XY_CODE)) {
                bracelet.setBloodPressure(handleValue(braceletInfo));
            } else if (Objects.equals(braceletInfo.getDataCode(), BusinessConstants.WD_CODE)) {
                bracelet.setTemp(handleValue(braceletInfo));
            }
        }
        vo.setBracelet(bracelet);
        return vo;
    }

    /**
     * 血压、心率、温度赋值
     *
     * @param braceletInfo
     * @return String
     * @author cwchen
     * @date 2024/8/15 18:12
     */
    public String handleValue(PersonControlVo.BraceletInfo braceletInfo) {
        String dataVal = braceletInfo.getDataVal();
        String dataUnit = braceletInfo.getDataUnit();
        if (StringUtils.isNotBlank(dataVal) && dataUnit == null) {
            return dataVal;
        } else if (StringUtils.isBlank(dataVal) && StringUtils.isNotBlank(dataUnit)) {
            return "--" + dataUnit;
        } else if (StringUtils.isNotBlank(dataVal) && StringUtils.isNotBlank(dataUnit)) {
            return dataVal + dataUnit;
        }
        return "--";
    }

    /**
     * 电量赋值
     *
     * @param braceletInfo
     * @return String
     * @author cwchen
     * @date 2024/8/15 18:12
     */
    public Double handleElecValue(PersonControlVo.BraceletInfo braceletInfo) {
        String dataVal = braceletInfo.getDataVal();
        if (StringUtils.isEmpty(dataVal) || !isNumeric(String.valueOf(dataVal))) {
            return 0D;
        } else {
            return Double.parseDouble(String.valueOf(dataVal));
        }
    }

    /**
     * 判断数值是否是数字类型
     *
     * @param str
     * @return boolean
     * @author cwchen
     * @date 2024/8/15 18:19
     */
    public static boolean isNumeric(String str) {
        try {
            Double.parseDouble(str);
            return true;
        } catch (NumberFormatException e) {
            return false;
        }
    }
}
