package com.yuchen.saas.park.service.service.elevator.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import com.alibaba.csp.sentinel.util.StringUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.thinkunion.sdk.iot.bean.api.CallingDeviceServiceResponse;
import com.yuchen.saas.device.api.dto.deviceCenter.SyncDeviceDataDeleteReqDTO;
import com.yuchen.saas.device.api.dto.deviceCenter.SyncDeviceDataSubmitReqDTO;
import com.yuchen.saas.device.api.entity.deviceCenter.SaasDeviceSmartHardware;
import com.yuchen.saas.device.api.feign.deviceCenter.DeviceCenterFeign;
import com.yuchen.saas.message.api.dto.WebSocketMessagDTO;
import com.yuchen.saas.message.api.feign.ws.WebSocketFeignServer;
import com.yuchen.saas.park.api.dto.elevator.ElevatorPointDTO;
import com.yuchen.saas.park.api.dto.elevator.SelectListDTO;
import com.yuchen.saas.park.api.dto.elevator.SelectListDetailDTO;
import com.yuchen.saas.park.api.dto.elevator.iot.request.IotDeviceInfoRequestDTO;
import com.yuchen.saas.park.api.dto.elevator.iot.request.ParameterDTO;
import com.yuchen.saas.park.api.dto.elevator.iot.request.QueryInfoDTO;
import com.yuchen.saas.park.api.dto.park.IoTEvent;
import com.yuchen.saas.park.api.dto.pldoor.CallDeviceServiceDto;
import com.yuchen.saas.park.api.entity.elevator.SaasParkElevatorManageLocationEntity;
import com.yuchen.saas.park.api.entity.elevator.SaasParkElevatorMonitorRunningStateEntity;
import com.yuchen.saas.park.api.entity.elevator.SaasParkElevatorPermissionElevatorGroup;
import com.yuchen.saas.park.api.entity.park.PmgBatParkInfo;
import com.yuchen.saas.park.api.entity.property.PropertyBuildingUnit;
import com.yuchen.saas.park.api.entity.property.PropertyBuildings;
import com.yuchen.saas.park.api.request.ElevatorPointRequest;
import com.yuchen.saas.park.api.response.ElevatorPointResponse;
import com.yuchen.saas.park.api.response.ThirdElevatorPointResponse;
import com.yuchen.saas.park.service.iot.IoTRemoteService;
import com.yuchen.saas.park.service.mapper.elevator.SaasParkElevatorManageLocationMapper;
import com.yuchen.saas.park.service.mapper.elevator.SaasParkElevatorMonitorRunningStateMapper;
import com.yuchen.saas.park.service.mapper.elevator.SaasParkElevatorPermissionElevatorGroupMapper;
import com.yuchen.saas.park.service.mapper.property.PropertyBuildingUnitMapper;
import com.yuchen.saas.park.service.mapper.property.PropertyBuildingsMapper;
import com.yuchen.saas.park.service.service.PmgBatParkInfoService;
import com.yuchen.saas.park.service.service.elevator.ISaasParkElevatorManageLocationService;
import lombok.extern.slf4j.Slf4j;
import org.nest.springwrap.core.log.exception.ServiceException;
import org.nest.springwrap.core.mp.base.BaseEntity;
import org.nest.springwrap.core.mp.base.BaseServiceImpl;
import org.nest.springwrap.core.mp.support.Condition;
import org.nest.springwrap.core.mp.support.Query;
import org.nest.springwrap.core.secure.utils.AuthUtil;
import org.nest.springwrap.core.tool.api.R;
import org.nest.springwrap.core.tool.utils.Func;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

/**
 * <p>
 * 梯控-电梯点 服务实现类
 * </p>
 *
 * @author baichaojie
 * @since 2024-06-25
 */
@Service
@Slf4j
public class SaasParkElevatorManageLocationServiceImpl extends BaseServiceImpl<SaasParkElevatorManageLocationMapper, SaasParkElevatorManageLocationEntity> implements ISaasParkElevatorManageLocationService {

    @Resource
    private IoTRemoteService ioTRemoteService;

    @Resource
    private SaasParkElevatorPermissionElevatorGroupMapper saasParkElevatorPermissionElevatorGroupMapper;


    @Resource
    private SaasParkElevatorMonitorRunningStateMapper saasParkElevatorMonitorRunningStateMapper;

    @Resource
    private PmgBatParkInfoService pmgBatParkInfoService;

    @Resource
    private PropertyBuildingsMapper propertyBuildingsMapper;

    @Resource
    private PropertyBuildingUnitMapper propertyBuildingUnitMapper;

    @Resource
    private DeviceCenterFeign deviceCenterFeign;
    @Resource
    private WebSocketFeignServer webSocketFeignServer;

    /**
     * IOT设备查询能力
     */
    private final String queryInfo = "queryInfo";

    /**
     * IOT下发设备参数
     */
    private final String SETPARAMETER = "setParameter";


    //大类（1：视频监控，2：智能硬件，3：传感设备）
    private final String broadCategory = "2";


    @Override
    public R<IPage<ThirdElevatorPointResponse>> thirdList(ElevatorPointRequest qryDTO, Query query) {
        Page<SaasParkElevatorManageLocationEntity> page = new Page<>(query.getCurrent(), query.getSize());
        LambdaQueryWrapper<SaasParkElevatorManageLocationEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Func.isNotEmpty(qryDTO.getParkId()), SaasParkElevatorManageLocationEntity::getParkId, qryDTO.getParkId());
        queryWrapper.eq(Func.isNotEmpty(qryDTO.getBuildingId()), SaasParkElevatorManageLocationEntity::getBuildingId, qryDTO.getBuildingId());
        queryWrapper.eq(Func.isNotEmpty(qryDTO.getUnitId()), SaasParkElevatorManageLocationEntity::getUnitId, qryDTO.getUnitId());
        queryWrapper.like(Func.isNotEmpty(qryDTO.getElevatorName()), SaasParkElevatorManageLocationEntity::getElevatorName, qryDTO.getElevatorName());
        queryWrapper.eq(Func.isNotEmpty(qryDTO.getIsEnabled()), SaasParkElevatorManageLocationEntity::getIsEnabled, qryDTO.getIsEnabled());
        queryWrapper.eq(Func.isNotEmpty(qryDTO.getOnlineStatus()), SaasParkElevatorManageLocationEntity::getOnlineStatus, qryDTO.getOnlineStatus());
        //queryWrapper.eq(Func.isNotEmpty(qryDTO.getGroupId(),SaasParkElevatorManageLocationEntity::getGroupNo,qryDTO.getGroupId());


        queryWrapper.orderByDesc(SaasParkElevatorManageLocationEntity::getCreateTime);

        IPage<SaasParkElevatorManageLocationEntity> pages = this.page(page, queryWrapper);

        List<SaasParkElevatorManageLocationEntity> saasParkElevatorManageLocationList = pages.getRecords();


        if (saasParkElevatorManageLocationList.isEmpty()) {
            return R.data(Condition.getPage(query));
        }

        //组装返回response
        IPage<ThirdElevatorPointResponse> pageVo = new Page(pages.getCurrent(), pages.getSize(), pages.getTotal());
        List<ThirdElevatorPointResponse> records = this.thirdListVO(pages.getRecords(), qryDTO);

        pageVo.setRecords(records);
        return R.data(pageVo);
    }


    @Override
    public R<IPage<ElevatorPointResponse>> list(ElevatorPointRequest qryDTO, Query query) {
        Page<SaasParkElevatorManageLocationEntity> page = new Page<>(query.getCurrent(), query.getSize());
        LambdaQueryWrapper<SaasParkElevatorManageLocationEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Func.isNotEmpty(qryDTO.getParkId()), SaasParkElevatorManageLocationEntity::getParkId, qryDTO.getParkId());
        queryWrapper.eq(Func.isNotEmpty(qryDTO.getBuildingId()), SaasParkElevatorManageLocationEntity::getBuildingId, qryDTO.getBuildingId());
        queryWrapper.eq(Func.isNotEmpty(qryDTO.getUnitId()), SaasParkElevatorManageLocationEntity::getUnitId, qryDTO.getUnitId());
        queryWrapper.like(Func.isNotEmpty(qryDTO.getElevatorName()), SaasParkElevatorManageLocationEntity::getElevatorName, qryDTO.getElevatorName());
        queryWrapper.eq(Func.isNotEmpty(qryDTO.getIsEnabled()), SaasParkElevatorManageLocationEntity::getIsEnabled, qryDTO.getIsEnabled());
        queryWrapper.eq(Func.isNotEmpty(qryDTO.getOnlineStatus()), SaasParkElevatorManageLocationEntity::getOnlineStatus, qryDTO.getOnlineStatus());
        //queryWrapper.eq(Func.isNotEmpty(qryDTO.getGroupId(),SaasParkElevatorManageLocationEntity::getGroupNo,qryDTO.getGroupId());


        queryWrapper.orderByDesc(SaasParkElevatorManageLocationEntity::getCreateTime);

        IPage<SaasParkElevatorManageLocationEntity> pages = this.page(page, queryWrapper);

        List<SaasParkElevatorManageLocationEntity> saasParkElevatorManageLocationList = pages.getRecords();


        if (saasParkElevatorManageLocationList.isEmpty()) {
            return R.data(Condition.getPage(query));
        }

        //组装返回response
        IPage<ElevatorPointResponse> pageVo = new Page(pages.getCurrent(), pages.getSize(), pages.getTotal());
        List<ElevatorPointResponse> records = this.listVO(pages.getRecords(), qryDTO);

        pageVo.setRecords(records);
        return R.data(pageVo);
    }

    public List<ElevatorPointResponse> listVO(List<SaasParkElevatorManageLocationEntity> listRecords, ElevatorPointRequest qryDTO) {
//        return (List) listRecords.stream().map(entity -> {
//            ElevatorPointResponse elevatorPointResponse = detail(entity.getId(), entity).getData();
//            return elevatorPointResponse;
//        }).filter((x)->x.getGroups().contains(qryDTO.getGroupId())).collect(Collectors.toList());

        List<ElevatorPointResponse> collect = listRecords.stream().map(entity -> {
            ElevatorPointResponse elevatorPointResponse = detail(entity.getId(), entity).getData();
            return elevatorPointResponse;
        }).collect(Collectors.toList());
        //过滤掉不包含组id的
        List<ElevatorPointResponse> newList = new ArrayList<>();

        if (StringUtil.isNotEmpty(qryDTO.getGroupId())) {
            for (ElevatorPointResponse elevatorPointResponse : collect) {
                for (SaasParkElevatorPermissionElevatorGroup saasParkElevatorPermissionElevatorGroup : elevatorPointResponse.getGroups()) {
                    if (saasParkElevatorPermissionElevatorGroup.getId() != null) {
                        if (saasParkElevatorPermissionElevatorGroup.getId().toString().equals(qryDTO.getGroupId())) {
                            newList.add(elevatorPointResponse);
                            break;
                        }
                    }
                }
            }
        } else {
            newList = collect;
        }
        return newList;

    }


    public List<ThirdElevatorPointResponse> thirdListVO(List<SaasParkElevatorManageLocationEntity> listRecords, ElevatorPointRequest qryDTO) {

        List<ThirdElevatorPointResponse> collect = listRecords.stream().map(entity -> {
            ThirdElevatorPointResponse elevatorPointResponse = thirdDetail(entity.getId(), entity).getData();
            return elevatorPointResponse;
        }).collect(Collectors.toList());
//        //过滤掉不包含组id的
//        List<ThirdElevatorPointResponse> newList = new ArrayList<>();
//
//        if (StringUtil.isNotEmpty(qryDTO.getGroupId())) {
//            for (ThirdElevatorPointResponse elevatorPointResponse : collect) {
//                for (SaasParkElevatorPermissionElevatorGroup saasParkElevatorPermissionElevatorGroup : elevatorPointResponse.getGroups()) {
//                    if (saasParkElevatorPermissionElevatorGroup.getId() != null) {
//                        if (saasParkElevatorPermissionElevatorGroup.getId().toString().equals(qryDTO.getGroupId())) {
//                            newList.add(elevatorPointResponse);
//                            break;
//                        }
//                    }
//                }
//            }
//        } else {
//            newList = collect;
//        }
//        return newList;
        return collect;
    }

    public R<ThirdElevatorPointResponse> thirdDetail(Long id, SaasParkElevatorManageLocationEntity saasParkElevatorManageLocationEntity) {
        ThirdElevatorPointResponse elevatorPointResponse = new ThirdElevatorPointResponse();
        BeanUtils.copyProperties(saasParkElevatorManageLocationEntity, elevatorPointResponse);

        //查出这个设备在电梯组中的存在于几个组,并把组信息返回
        List<SaasParkElevatorPermissionElevatorGroup> groupByElevatorId = saasParkElevatorPermissionElevatorGroupMapper.getGroupByElevatorId(id.toString());
        //elevatorPointResponse.setGroups(groupByElevatorId);

        String levatorRangeStr = "";
        for (int i = 0; i < groupByElevatorId.size(); i++) {
            if (i != groupByElevatorId.size() - 1) {
                levatorRangeStr += groupByElevatorId.get(i).getGroupName() + ",";
            } else {
                levatorRangeStr += groupByElevatorId.get(i).getGroupName();
            }
        }

        PmgBatParkInfo parkInfo = pmgBatParkInfoService.getById(saasParkElevatorManageLocationEntity.getParkId());
        if (Func.isNotEmpty(parkInfo)) {
            elevatorPointResponse.setParkName(parkInfo.getParkName());
        }


//        elevatorPointResponse.setGroupNamesStr(levatorRangeStr);
//
//        ElevatorPointResponse elevatorPoint = baseMapper.getElevatorPoint(saasParkElevatorManageLocationEntity);
//        if (elevatorPoint != null) {
//            elevatorPointResponse.setProductName(elevatorPoint.getProductName());
//        }


        PropertyBuildings propertyBuildings = propertyBuildingsMapper.selectById(saasParkElevatorManageLocationEntity.getBuildingId());
        if (propertyBuildings != null) {
            elevatorPointResponse.setBuildingName(propertyBuildings.getBuildingName());
        }

        PropertyBuildingUnit propertyBuildingUnit = propertyBuildingUnitMapper.selectById(saasParkElevatorManageLocationEntity.getUnitId());
        if (propertyBuildingUnit != null) {
            elevatorPointResponse.setUnitName(propertyBuildingUnit.getUnitName());
        }


        return R.data(elevatorPointResponse);
    }


    public R<ElevatorPointResponse> detail(Long id, SaasParkElevatorManageLocationEntity saasParkElevatorManageLocationEntity) {
        ElevatorPointResponse elevatorPointResponse = new ElevatorPointResponse();
        BeanUtils.copyProperties(saasParkElevatorManageLocationEntity, elevatorPointResponse);

        //查出这个设备在电梯组中的存在于几个组,并把组信息返回
        List<SaasParkElevatorPermissionElevatorGroup> groupByElevatorId = saasParkElevatorPermissionElevatorGroupMapper.getGroupByElevatorId(id.toString());
        elevatorPointResponse.setGroups(groupByElevatorId);

        String levatorRangeStr = "";
        for (int i = 0; i < groupByElevatorId.size(); i++) {
            if (i != groupByElevatorId.size() - 1) {
                levatorRangeStr += groupByElevatorId.get(i).getGroupName() + ",";
            } else {
                levatorRangeStr += groupByElevatorId.get(i).getGroupName();
            }
        }

        PmgBatParkInfo parkInfo = pmgBatParkInfoService.getById(saasParkElevatorManageLocationEntity.getParkId());
        if (Func.isNotEmpty(parkInfo)) {
            elevatorPointResponse.setParkName(parkInfo.getParkName());
        }


        elevatorPointResponse.setGroupNamesStr(levatorRangeStr);

        ElevatorPointResponse elevatorPoint = baseMapper.getElevatorPoint(saasParkElevatorManageLocationEntity);
        if (elevatorPoint != null) {
            elevatorPointResponse.setProductName(elevatorPoint.getProductName());
        }


        PropertyBuildings propertyBuildings = propertyBuildingsMapper.selectById(saasParkElevatorManageLocationEntity.getBuildingId());
        if (propertyBuildings != null) {
            elevatorPointResponse.setBuildingName(propertyBuildings.getBuildingName());
        }

        PropertyBuildingUnit propertyBuildingUnit = propertyBuildingUnitMapper.selectById(saasParkElevatorManageLocationEntity.getUnitId());
        if (propertyBuildingUnit != null) {
            elevatorPointResponse.setUnitName(propertyBuildingUnit.getUnitName());
        }


        return R.data(elevatorPointResponse);
    }


    private String queryIotDevice(String deviceDid, String productKey) {
        CallDeviceServiceDto callDeviceServiceDto = new CallDeviceServiceDto();
        callDeviceServiceDto.setIdentify(queryInfo);
        callDeviceServiceDto.setDeviceName(deviceDid);
        callDeviceServiceDto.setProductKey(productKey);

        IotDeviceInfoRequestDTO reqs = new IotDeviceInfoRequestDTO();
        reqs.setPageNum(1);


        String mess = "";
        try {
            mess = getDevice(callDeviceServiceDto, reqs);
        } catch (Exception ex) {

        }
        return mess;

    }

    /**
     * 电梯点新增或者编辑 逻辑
     * 1、判断过滤,参数校验,看看要新增或者修改的IOT设备名称是否已经存在
     * 2、判断电梯监测状态表里是否有设备的在离线状态,有的话拿过来用,没有的话默认离线0
     * 3、保存
     * //4、暂时不查询设备
     * //5、暂时不设置参数
     * 6、同步设备到智能硬件中心
     *
     * @param reqDTO
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean saveOrUpdateByParam(ElevatorPointDTO reqDTO) {

        boolean b = false;
        SaasParkElevatorManageLocationEntity saasParkElevatorManageLocationEntity = new SaasParkElevatorManageLocationEntity();
        BeanUtil.copyProperties(reqDTO, saasParkElevatorManageLocationEntity);

        // 判断过滤,参数校验,看看要新增或者修改的IOT设备名称是否已经存在
        validRepeat(saasParkElevatorManageLocationEntity);


        //查询出设备状态
        SaasParkElevatorMonitorRunningStateEntity saasParkElevatorMonitorRunningStateEntity = saasParkElevatorMonitorRunningStateMapper.selectOne(new LambdaQueryWrapper<SaasParkElevatorMonitorRunningStateEntity>().eq(SaasParkElevatorMonitorRunningStateEntity::getElevatorMokuaiId, reqDTO.getId()));

        String deviceStatus = "0";
        //判断电梯监测状态表里是否有设备的在离线状态
        if (saasParkElevatorMonitorRunningStateEntity != null) {
            if (saasParkElevatorMonitorRunningStateEntity.getIsOnline() == null) {
                deviceStatus = saasParkElevatorMonitorRunningStateEntity.getIsOnline() + "";

            }
        }

        if (reqDTO.getId() == null) {
            //如果是新增,
            b = save(saasParkElevatorManageLocationEntity);
            updateElevatorGroupBind(saasParkElevatorManageLocationEntity, reqDTO.getElevatorGroupIds());

        } else {
            //saasParkElevatorManageLocationEntity.setId(reqDTO.getId());
            updateElevatorGroupBind(saasParkElevatorManageLocationEntity, reqDTO.getElevatorGroupIds());
            b = updateById(saasParkElevatorManageLocationEntity);
        }

        saasParkElevatorManageLocationEntity.setOnlineStatus(deviceStatus);

        this.baseMapper.updateById(saasParkElevatorManageLocationEntity);


        //电梯状态表也同步新增一条
        SaasParkElevatorMonitorRunningStateEntity saasParkElevatorMonitorRunningState = saasParkElevatorMonitorRunningStateMapper.selectOne(new LambdaQueryWrapper<SaasParkElevatorMonitorRunningStateEntity>().eq(SaasParkElevatorMonitorRunningStateEntity::getElevatorMokuaiId, saasParkElevatorManageLocationEntity.getId()));

        if (saasParkElevatorMonitorRunningState == null) {
            //原本不存在,新增一条
            SaasParkElevatorMonitorRunningStateEntity newSaasParkElevatorMonitorRunningState=new SaasParkElevatorMonitorRunningStateEntity();
            newSaasParkElevatorMonitorRunningState.setElevatorMokuaiId(saasParkElevatorManageLocationEntity.getId());
            newSaasParkElevatorMonitorRunningState.setUpdateTime(new Date());
            newSaasParkElevatorMonitorRunningState.setParkId(saasParkElevatorManageLocationEntity.getParkId());
            newSaasParkElevatorMonitorRunningState.setUnitId(saasParkElevatorManageLocationEntity.getUnitId());
            newSaasParkElevatorMonitorRunningState.setBuildingId(saasParkElevatorManageLocationEntity.getBuildingId());
            newSaasParkElevatorMonitorRunningState.setCreateTime(new Date());
            newSaasParkElevatorMonitorRunningState.setIsOnline(0);
            newSaasParkElevatorMonitorRunningState.setIsDeleted(0);
            saasParkElevatorMonitorRunningStateMapper.insert(newSaasParkElevatorMonitorRunningState);
        }
        else {
            //原本存在,不管
        }


        //调用IOT查询设备
        //去IOT获取设备判断设备存在与否,把结果放到remark字段存储
        //String remark =queryIotDevice(saasParkElevatorManageLocationEntity.getDeviceName(),saasParkElevatorManageLocationEntity.getProductKey());
        //saasParkElevatorManageLocationEntity.setRemark(remark);


        //调用IOT设置电梯参数
        //boolean sendSetParameterResult = sendSetParameter(saasParkElevatorManageLocationEntity);


        //同步设备到智能硬件中心
        //syncDeviceData(reqDTO, deviceStatus);


        return b;

    }


    /**
     * 同步设备到智能硬件中心
     */
    private void syncDeviceData(ElevatorPointDTO elevatorPointDTO, String deviceStatus) {
        SyncDeviceDataSubmitReqDTO syncDeviceDataSubmitReqDTO = new SyncDeviceDataSubmitReqDTO();
        syncDeviceDataSubmitReqDTO.setBroadCategory(broadCategory);
        SaasDeviceSmartHardware saasDeviceSmartHardware = new SaasDeviceSmartHardware();
        saasDeviceSmartHardware.setCustomerId(AuthUtil.getUser().getCustomerManageId());
        saasDeviceSmartHardware.setProjectId(elevatorPointDTO.getParkId());
        //saasDeviceSmartHardware.setSpaceId();
        saasDeviceSmartHardware.setSmartHardwareType(elevatorPointDTO.getBroadCategory());
        saasDeviceSmartHardware.setProductKey(elevatorPointDTO.getProductKey());
        saasDeviceSmartHardware.setDeviceName(elevatorPointDTO.getDeviceName());
        saasDeviceSmartHardware.setDeviceImages("");
        saasDeviceSmartHardware.setDeviceState(deviceStatus);
        saasDeviceSmartHardware.setDeviceAlias(elevatorPointDTO.getDeviceName());
        saasDeviceSmartHardware.setDeviceAddress(elevatorPointDTO.getLocation());
        //saasDeviceSmartHardware.setLastConnectionTime();
        //saasDeviceSmartHardware.setLastBreakTime();
        //saasDeviceSmartHardware.setRemark();
        syncDeviceDataSubmitReqDTO.setSaasDeviceSmartHardware(saasDeviceSmartHardware);
        deviceCenterFeign.syncSubmitDeviceData(syncDeviceDataSubmitReqDTO);
    }


    /**
     * 同步删除设备到智能硬件中心
     */
    private void syncDeleteDeviceData(String deviceName) {
        SyncDeviceDataDeleteReqDTO reqDTO = new SyncDeviceDataDeleteReqDTO();
        reqDTO.setBroadCategory(broadCategory);
        reqDTO.setDeviceName(deviceName);
        deviceCenterFeign.syncDeleteDeviceData(reqDTO);
    }


    @Override
    public void updateElevatorLimit(SelectListDTO selectListDTO) {

        List<SelectListDetailDTO> listSelectListDetailDTO = selectListDTO.getSelectListDetailDTO();
        for (SelectListDetailDTO selectListDetailDTO : listSelectListDetailDTO) {
            if (selectListDetailDTO != null) {
                SaasParkElevatorManageLocationEntity saasParkElevatorManageLocationEntity = this.baseMapper.selectById(selectListDetailDTO.getId());
                saasParkElevatorManageLocationEntity.setIsEnabled(selectListDetailDTO.getIsEnabled());

                //调用IOT设置电梯参数
                boolean sendSetParameterResult = sendSetParameter(saasParkElevatorManageLocationEntity);
                if (sendSetParameterResult) {
                    this.baseMapper.updateById(saasParkElevatorManageLocationEntity);
                }
            }
        }
    }

    /**
     * 电梯参数设置
     *
     * @param saasParkElevatorManageLocationEntity
     * @return
     */
    @Override
    public boolean sendSetParameter(SaasParkElevatorManageLocationEntity saasParkElevatorManageLocationEntity) {

        CallDeviceServiceDto callDeviceServiceDto = new CallDeviceServiceDto();
        callDeviceServiceDto.setIdentify(SETPARAMETER);
        callDeviceServiceDto.setProductKey(saasParkElevatorManageLocationEntity.getProductKey());
        callDeviceServiceDto.setDeviceName(saasParkElevatorManageLocationEntity.getDeviceDid());
        Map<String, Object> in = new HashMap<>();
        try {

            ParameterDTO parameterDTO = new ParameterDTO();
            parameterDTO.setLiftMode(saasParkElevatorManageLocationEntity.getIsEnabled() ? 1 : 0);
            parameterDTO.setEventReportEnabled(1);
            parameterDTO.setDevDateTime(DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
            parameterDTO.setDevRestart(0);
            parameterDTO.setStateIntervalTime(1);
            //parameterDTO.setDeviceID(saasParkElevatorManageLocationEntity.getIotDeviceId());

            in.put("liftMode", parameterDTO.getLiftMode());
            in.put("eventReportEnabled", parameterDTO.getEventReportEnabled());
            in.put("stateIntervalTime", parameterDTO.getStateIntervalTime());
            in.put("devRestart", parameterDTO.getDevRestart());
            in.put("devDateTime", parameterDTO.getDevDateTime());
            //in.put("deviceID", parameterDTO.getDeviceID());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        callDeviceServiceDto.setParams(in);
        String json = JSONObject.toJSONString(callDeviceServiceDto);
        Map map = JSONObject.parseObject(json, Map.class);

        //调用接口
        log.info("====== 保存电梯参数设置信息参数：{}", json);
        CallingDeviceServiceResponse response = ioTRemoteService.callServiceReturn(map);
        if (Func.isNotEmpty(response)) {
            boolean result = false;
            String resultJson = JSONObject.toJSONString(response);
            log.info("====== 保存电梯参数设置返回数据：{}", resultJson);
            if (response.getCode().equals("200")) {
                result = true;
            }
            return result;
        }
        return false;


    }


    /***
     * 电梯组进行修改
     */
    private void updateElevatorGroupBind(SaasParkElevatorManageLocationEntity entity, List<Long> listNewElevatorGroup) {

        List<Long> listAdd = new ArrayList<>();
        List<Long> listReduce = new ArrayList<>();

        //1.查询原本的关联关系
        if (entity.getId() != null) {
            List<SaasParkElevatorPermissionElevatorGroup> groups = saasParkElevatorPermissionElevatorGroupMapper.getGroupByElevatorId(entity.getId().toString());

            List<Long> listOldElevatorGroup = new ArrayList<>();
            for (SaasParkElevatorPermissionElevatorGroup group : groups) {
                listOldElevatorGroup.add(group.getId());
            }
            if (listNewElevatorGroup == null) {
                throw new ServiceException("请选择组");
            }

            listAdd = getAddaListThanbList(listNewElevatorGroup, listOldElevatorGroup);
            listReduce = getReduceaListThanbList(listNewElevatorGroup, listOldElevatorGroup);

            //旧:组 1  2  3   //新:组 2   3        那么删除组1中的此设备
            //旧:组 1  2  3   //新:组 2   3   4    那么删除组1中的此设备,增加组4中此设备
            //旧:组 1  2  3   //新:组 1   2   3  4 那么增加组4中此设备
            //旧:组 1  2  3   //新:组 4   5   6    那么删除组123中的此设备,增加组456中此设备
            //旧:组           //新:组 4   5   6    增加组456中此设备
        } else {
            listAdd = listNewElevatorGroup;
        }


        for (Long groupId : listAdd) {
            //根据id增加组中的关联设备id
            updateElevatorGroupRange(groupId, entity.getId(), 1);
        }

        for (Long groupId : listReduce) {
            //根据id去除组中的关联设备id
            updateElevatorGroupRange(groupId, entity.getId(), -1);
        }
    }

    private void updateElevatorGroupRange(Long groupId, Long elevatorId, Integer type) {
        //查询出组id对应的组信息
        SaasParkElevatorPermissionElevatorGroup group = saasParkElevatorPermissionElevatorGroupMapper.selectById(groupId);
        if (group == null) {
            throw new ServiceException("请先添加组！");
        }
        if (StringUtil.isNotEmpty(group.getElevatorRange())) {
            String[] array = group.getElevatorRange().split(",");
            List<String> list = new ArrayList<>(Arrays.asList(array));
            if (type == 1) {
                list.add(elevatorId.toString());
            } else {
                list.remove(elevatorId.toString());
            }
            group.setElevatorRange(String.join(",", list));
        }
        saasParkElevatorPermissionElevatorGroupMapper.updateById(group);
    }


    /**
     * 判断要新增或者编辑设备名称是否存在了,存在提示不能重复
     *
     * @param saasParkElevatorManageLocationEntity
     */
    private void validRepeat(SaasParkElevatorManageLocationEntity saasParkElevatorManageLocationEntity) {
        //要新增的 或者 要修改的
        int count = count(new LambdaQueryWrapper<SaasParkElevatorManageLocationEntity>()
                .eq(SaasParkElevatorManageLocationEntity::getDeviceName, saasParkElevatorManageLocationEntity.getDeviceName())
                .notIn(Objects.nonNull(saasParkElevatorManageLocationEntity.getId()), BaseEntity::getId, saasParkElevatorManageLocationEntity.getId()));
        if (count > 0) {
            throw new ServiceException("设备名称不能重复");
        }
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public String deleteById(Long id) {
        String msg = "";

        //TODO 查询电梯点是否被引用
        /*List<DoorAccessControlConfigMapping> mappingList = doorAccessControlConfigMappingRepository.selectList(new LambdaQueryWrapper<DoorAccessControlConfigMapping>()
                .eq(DoorAccessControlConfigMapping::getDoorAccessControlRefId, id));
        if(Func.isNotEmpty(mappingList)){
            log.info("======门禁分组被引用");
            msg = "门禁分组被引用";
            return msg;
        }*/


        //进行逻辑删除
        // List ids = new ArrayList<>();
        // ids.add(id);
        //Boolean logicDelete = deleteLogic(ids);
        //if (!logicDelete) {
        //   msg = "删除失败";
        //}
        // return msg;
        List ids = new ArrayList<>();
        ids.add(id);
        //int result = this.baseMapper.deleteById(saasParkElevatorManageLocationEntity.getId());
        Boolean logicDelete = deleteLogic(ids);
        if (logicDelete) {
            msg = "";


            SaasParkElevatorManageLocationEntity saasParkElevatorManageLocationEntity = this.getOne(Wrappers.<SaasParkElevatorManageLocationEntity>lambdaQuery()
                    .eq(SaasParkElevatorManageLocationEntity::getId, id).last("limit 1"));

            if (saasParkElevatorManageLocationEntity != null) {
                syncDeleteDeviceData(saasParkElevatorManageLocationEntity.getElevatorName());
            }
        } else {
            msg = "删除失败";
        }
        return msg;
    }

    @Override
    public R<IPage<ElevatorPointResponse>> getIotElevatorList() {

        CallDeviceServiceDto callDeviceServiceDto = new CallDeviceServiceDto();
        callDeviceServiceDto.setIdentify("queryInfo");
        callDeviceServiceDto.setProductKey("ZdeLdKGCsgNcM6Pw");
        callDeviceServiceDto.setDeviceName("WxTWtxTjvX4TkXUu");
        Map<String, Object> in = new HashMap<>();
        try {

            QueryInfoDTO queryInfoDTO = new QueryInfoDTO();
            queryInfoDTO.setPageNum(1);
            in.put("pageNum", queryInfoDTO.getPageNum());

        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        callDeviceServiceDto.setParams(in);
        String json = JSONObject.toJSONString(callDeviceServiceDto);
        Map map = JSONObject.parseObject(json, Map.class);

        //调用接口
        log.info("====== 设备查询参数：{}", json);
        CallingDeviceServiceResponse response = ioTRemoteService.callServiceReturn(map);
        if (Func.isNotEmpty(response)) {

            String resultJson = JSONObject.toJSONString(response);
            log.info("====== 设备查询返回数据：{}", resultJson);
            if (response.getCode().equals("200")) {
                //IotDeviceInfoDTO
            }

        }


        return null;
    }

    @Override
    public boolean receiveIotEventInfo(IoTEvent ioTEvent) {
        LambdaQueryWrapper<SaasParkElevatorManageLocationEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SaasParkElevatorManageLocationEntity::getProductKey, ioTEvent.getProductKey());
        wrapper.eq(SaasParkElevatorManageLocationEntity::getDeviceName, ioTEvent.getDeviceName());
        SaasParkElevatorManageLocationEntity elevatorManageLocation = this.getOne(wrapper);
        if (Func.isNotEmpty(elevatorManageLocation)) {
            //构建ws弹窗结构体
            WebSocketMessagDTO<IoTEvent> messageDto = new WebSocketMessagDTO<>(String.valueOf(elevatorManageLocation.getParkId()), "/event", ioTEvent);
            //发送ws
            R<Boolean> r = webSocketFeignServer.convertAndSendToUser(messageDto);
            if (r != null && r.getCode() == 200 && r.getData() != null && r.getData()) {
                log.info("ws推送成功");
            } else {
                log.info("ws消息推送失败");
            }
        }
        return true;
    }


//    @Override
//    public Boolean saveOrUpdateElevatorStatusByParam(ElevatorStatusDTO elevatorStatusDTO) {
//        SaasParkElevatorManageLocationEntity saasParkElevatorManageLocationEntity = this.baseMapper.selectById(elevatorStatusDTO.getId());
//        if (saasParkElevatorManageLocationEntity != null) {
//            saasParkElevatorManageLocationEntity.setIsEnabled(elevatorStatusDTO.getElevatorOpenOrClose() == ElevatorConstant.ElevatorEnabled.IS_DISABLED ? false : true);
//        }
//
//        CallDeviceServiceDto callDeviceServiceDto = new CallDeviceServiceDto();
//        callDeviceServiceDto.setIdentify(setParameter);
//        //callDeviceServiceDto.setProductKey();
//
//        IotDeviceParamRequestDTO reqs = new IotDeviceParamRequestDTO();
//        //TODO 相关数据对应接入
//        boolean resultDownLoadIot = setParameter(callDeviceServiceDto, reqs);
//        if (resultDownLoadIot) {
//            return updateById(saasParkElevatorManageLocationEntity);
//        }
//        return false;
//    }


    /**
     * 调用IOT的queryInfo能力
     *
     * @param callDeviceServiceDto
     * @return
     */
    private String getDevice(CallDeviceServiceDto callDeviceServiceDto, IotDeviceInfoRequestDTO reqs) {
        String reqJson = JSONObject.toJSONString(reqs);
        Map params = JSONObject.parseObject(reqJson, Map.class);
        callDeviceServiceDto.setParams(params);
        String json = JSONObject.toJSONString(callDeviceServiceDto);
        Map map = JSONObject.parseObject(json, Map.class);
        //调用接口
        log.info("====== 调用iot下发获取设备参数：{}", json);
        CallingDeviceServiceResponse response = ioTRemoteService.callServiceReturn(map);
        if (Func.isNotEmpty(response)) {

            String resultJson = JSONObject.toJSONString(response);
            log.info("====== 调用iot下发获取设备返回：{}", resultJson);
//            if (response.getCode().equals("200")) {
//                return response.getData().size() > 0;
//            } else {
//
//            }
            return "下发跟接收:" + json + "#" + resultJson;

        } else {
            return "其他异常";
        }


    }


    /**
     * @param aList 本列表
     * @param bList 对照列表
     * @return 返回增加的元素组成的列表
     * @Description: 计算列表aList相对于bList的增加的情况，兼容任何类型元素的列表数据结构
     */
    public static <E> List<E> getAddaListThanbList(List<E> aList, List<E> bList) {
        List<E> addList = new ArrayList<E>();
        for (int i = 0; i < aList.size(); i++) {
            if (!myListContains(bList, aList.get(i))) {
                addList.add(aList.get(i));
            }
        }
        return addList;
    }

    /**
     * @param aList 本列表
     * @param bList 对照列表
     * @return 返回减少的元素组成的列表
     * @Description: 计算列表aList相对于bList的减少的情况，兼容任何类型元素的列表数据结构
     */
    public static <E> List<E> getReduceaListThanbList(List<E> aList, List<E> bList) {
        List<E> reduceaList = new ArrayList<E>();
        for (int i = 0; i < bList.size(); i++) {
            if (!myListContains(aList, bList.get(i))) {
                reduceaList.add(bList.get(i));
            }
        }
        return reduceaList;
    }


    /**
     * @param sourceList 源列表
     * @param element    待判断的包含元素
     * @return 包含返回 true，不包含返回 false
     * @Description: 判断元素element是否是sourceList列表中的一个子元素
     */
    private static <E> boolean myListContains(List<E> sourceList, E element) {
        if (sourceList == null || element == null) {
            return false;
        }
        if (sourceList.isEmpty()) {
            return false;
        }
        for (E tip : sourceList) {
            if (element.equals(tip)) {
                return true;
            }
        }
        return false;
    }

    /**
     * @param list
     * @return list
     * @Description: 去除list重复数据
     */
    public static <E> List<E> cleanDisRepet(List<E> list) {
        HashSet h = new HashSet(list);
        list.clear();
        list.addAll(h);
        return list;
    }


}



