package com.njcn.csdevice.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.njcn.common.pojo.exception.BusinessException;
import com.njcn.csdevice.api.CsCommTerminalFeignClient;
import com.njcn.csdevice.enums.AlgorithmResponseEnum;
import com.njcn.csdevice.mapper.CsDeviceUserPOMapper;
import com.njcn.csdevice.mapper.CsEquipmentDeliveryMapper;
import com.njcn.csdevice.mapper.CsMarketDataMapper;
import com.njcn.csdevice.pojo.dto.DevDetailDTO;
import com.njcn.csdevice.pojo.param.UserDevParam;
import com.njcn.csdevice.pojo.po.*;
import com.njcn.csdevice.pojo.vo.CsLedgerVO;
import com.njcn.csdevice.pojo.vo.CsTouristDataParmVO;
import com.njcn.csdevice.pojo.vo.DevCountVO;
import com.njcn.csdevice.pojo.vo.DevUserVO;
import com.njcn.csdevice.service.*;
import com.njcn.csharmonic.api.EventUserFeignClient;
import com.njcn.csharmonic.param.CsEventUserQueryParam;
import com.njcn.harmonic.utils.PublicDataUtils;
import com.njcn.user.api.UserFeignClient;
import com.njcn.user.enums.AppRoleEnum;
import com.njcn.user.pojo.po.User;
import com.njcn.web.utils.RequestUtil;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;

import static java.util.Objects.isNull;

/**
 * 
 * Description:
 * Date: 2023/6/27  9:40【需求编号】
 *
 * @author clam
 * @version V1.0.0
 */
@Service
@RequiredArgsConstructor
public class CsDeviceUserPOServiceImpl extends ServiceImpl<CsDeviceUserPOMapper, CsDeviceUserPO> implements CsDeviceUserPOService{

    private final CsDevModelRelationService csDevModelRelationService;
    private final ICsLedgerService iCsLedgerService;
    private final CsEquipmentDeliveryMapper csEquipmentDeliveryMapper;
    private final AppLineTopologyDiagramService appLineTopologyDiagramService;
    private final CsTouristDataPOService csTouristDataPOService;
    private final CsLinePOService csLinePOService;
    private final CsMarketDataMapper csMarketDataMapper;
    private final EventUserFeignClient eventUserFeignClient;
    private final UserFeignClient userFeignClient;
    private final IMqttUserService mqttUserService;
    private final CsCommTerminalFeignClient commTerminalService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean add(String id) {
        CsDeviceUserPO one = this.lambdaQuery().eq(CsDeviceUserPO::getDeviceId, id).one();
        if(!isNull(one)){
            throw new BusinessException(AlgorithmResponseEnum.LOSE_EFFICACY);
        }
        String userIndex = RequestUtil.getUserIndex();
        CsDeviceUserPO csDevice = new CsDeviceUserPO();
        //设备PrimaryUserId与SubUserId相同就是主用户
        csDevice.setDeviceId(id);
        csDevice.setPrimaryUserId(userIndex);
        csDevice.setSubUserId(userIndex);
        csDevice.setStatus("1");
        boolean save = this.save(csDevice);
        return save;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean share(List<String> ids) {
        ids.stream().forEach(id->{
            List<CsDeviceUserPO> list = this.lambdaQuery().eq(CsDeviceUserPO::getDeviceId, id).eq(CsDeviceUserPO::getStatus,"1" ).list();

            if(CollectionUtils.isEmpty(list)){
                throw new BusinessException(AlgorithmResponseEnum.DATA_LOSE);

            }
            String userIndex = RequestUtil.getUserIndex();
            String userRole = RequestUtil.getUserRole();
            List<String> strings = JSONArray.parseArray(userRole, String.class);
            if(CollectionUtils.isEmpty(strings)){
                throw new BusinessException(AlgorithmResponseEnum.UNKNOW_ROLE);

            }
            userRole=strings.get(0);
            //分享只能给vip用户分享
            if(
                    !Objects.equals(userRole, AppRoleEnum.APP_VIP_USER.getCode())
            ){
                throw new BusinessException(AlgorithmResponseEnum.UNKNOW_ROLE);

            }
            CsDeviceUserPO one = this.lambdaQuery().eq(CsDeviceUserPO::getDeviceId, id).eq(CsDeviceUserPO::getStatus,"1" ).eq(CsDeviceUserPO::getSubUserId,userIndex).one();
            if(!isNull(one)){
                return;
            }
            CsDeviceUserPO csDeviceUserPO = list.get(0);
            csDeviceUserPO.setSubUserId(userIndex);
            boolean save = this.save(csDeviceUserPO);
        });


        return true;
    }

    @Override
    public DevCountVO devCount(String id,String time) {
        DevCountVO vo = new DevCountVO();
        //获取app用户的台账树，包含四个层级 工程、项目、设备、监测点
        List<CsLedgerVO> appLedger = iCsLedgerService.appLineTree();
        //判断当前用户，如果是游客，则需要筛选数据,只保留游客的数据
        String roleString = RequestUtil.getUserRole();
        if (roleString.contains(AppRoleEnum.TOURIST.getCode())) {
            List<CsTouristDataParmVO> csTouristDataParmVOList = csTouristDataPOService.queryAll();
            if (CollectionUtil.isNotEmpty(csTouristDataParmVOList)) {
                List<String> devList = csTouristDataParmVOList.stream().map(CsTouristDataParmVO::getDeviceId).collect(Collectors.toList());
                // 保留游客有权限的工程、项目、设备、监测点数据
                appLedger = appLedger.stream()
                        .filter(engineering -> {
                            boolean hasValidProject = false;
                            if (CollectionUtil.isNotEmpty(engineering.getChildren())) {
                                List<CsLedgerVO> validProjects = engineering.getChildren().stream()
                                        .filter(project -> {
                                            boolean hasValidDevice = false;
                                            if (CollectionUtil.isNotEmpty(project.getChildren())) {
                                                List<CsLedgerVO> validDevices = project.getChildren().stream()
                                                        .filter(device -> devList.contains(device.getId()))
                                                        .collect(Collectors.toList());
                                                project.setChildren(validDevices);
                                                hasValidDevice = CollectionUtil.isNotEmpty(validDevices);
                                            }
                                            return hasValidDevice;
                                        })
                                        .collect(Collectors.toList());
                                engineering.setChildren(validProjects);
                                hasValidProject = CollectionUtil.isNotEmpty(validProjects);
                            }
                            return hasValidProject;
                        })
                        .collect(Collectors.toList());
            } else {
                // 如果游客没有配置任何数据权限，返回空列表
                appLedger = new ArrayList<>();
            }
        } else {
            //根据用户获取所属的设备
            List<String> lineIds = commTerminalService.getLineIdsByUser(RequestUtil.getUserIndex()).getData();
            if (CollectionUtil.isEmpty(lineIds)) {
                return vo;
            }
            Set<String> targetLineIds = new HashSet<>(lineIds);
            appLedger = filterLedgerTree(appLedger, targetLineIds);
        }

        if (CollectionUtil.isNotEmpty(appLedger)) {
            //获取第一层项目层级
            List<CsLedgerVO> firstLevelList = new ArrayList<>();
            //获取第三层设备层级
            List<CsLedgerVO> thirdLevelList = new ArrayList<>();
            //获取第四层设备层级
            List<CsLedgerVO> forthLevelList = new ArrayList<>();
            for (CsLedgerVO firstLevel : appLedger) {
                firstLevelList.add(firstLevel);
                if (CollectionUtil.isNotEmpty(firstLevel.getChildren())) {
                    for (CsLedgerVO secondLevel : firstLevel.getChildren()) {
                        if (CollectionUtil.isNotEmpty(secondLevel.getChildren())) {
                            thirdLevelList.addAll(secondLevel.getChildren());
                            for (CsLedgerVO threeLevel : secondLevel.getChildren()) {
                                if (CollectionUtil.isNotEmpty(threeLevel.getChildren())) {
                                    forthLevelList.addAll(threeLevel.getChildren());
                                }
                            }

                        }
                    }
                }
            }
            //note 所有工程数据
            //获取工程数量
            if (CollectionUtil.isNotEmpty(firstLevelList)) {
                vo.setEningerCount(firstLevelList.size());
            }

            //获取设备总数、在线设备、离线设备
            if (CollectionUtil.isNotEmpty(thirdLevelList)) {
                List<String> devIds = thirdLevelList.stream().map(CsLedgerVO::getId).collect(Collectors.toList());
                List<CsEquipmentDeliveryPO> devList = csEquipmentDeliveryMapper.selectBatchIds(devIds);
                //在线设备
                List<CsEquipmentDeliveryPO> onlineDevs = devList.stream().filter(dev -> Objects.equals(dev.getRunStatus(), 2)).collect(Collectors.toList());
                if (CollectionUtil.isNotEmpty(onlineDevs)) {
                    vo.setOnLineDevCount(onlineDevs.size());
                    vo.setOnLineDevs(onlineDevs);
                }
                //离线设备
                List<CsEquipmentDeliveryPO> offlineDevs = devList.stream().filter(dev -> Objects.equals(dev.getRunStatus(), 1)).collect(Collectors.toList());
                if (CollectionUtil.isNotEmpty(offlineDevs)) {
                    vo.setOffLineDevCount(offlineDevs.size());
                    vo.setOffLineDevs(offlineDevs);
                }
            } else {
                return vo;
            }
            //获取未读事件数量
            if (CollectionUtil.isNotEmpty(forthLevelList)) {
                CsEventUserQueryParam param1 = new CsEventUserQueryParam();
                param1.setUserId(RequestUtil.getUserIndex());
                param1.setStartTime(PublicDataUtils.calculateMonthStart(time));
                param1.setEndTime(PublicDataUtils.calculateMonthEnd(time));
                param1.setEventIds(forthLevelList.stream().map(CsLedgerVO::getId).collect(Collectors.toList()));

                List<String> eventCount = eventUserFeignClient.queryTempEvent(param1).getData();
                vo.setEventCount(CollectionUtil.isNotEmpty(eventCount)?eventCount.size():0);
                List<String> harmonicCount = eventUserFeignClient.queryTempHarmonic(param1).getData();
                vo.setHarmonicCount(CollectionUtil.isNotEmpty(harmonicCount)?harmonicCount.size():0);
            }
            if (CollectionUtil.isNotEmpty(thirdLevelList)) {
                CsEventUserQueryParam param1 = new CsEventUserQueryParam();
                param1.setUserId(RequestUtil.getUserIndex());
                param1.setStartTime(PublicDataUtils.calculateMonthStart(time));
                param1.setEndTime(PublicDataUtils.calculateMonthEnd(time));
                param1.setEventIds(thirdLevelList.stream().map(CsLedgerVO::getId).collect(Collectors.toList()));

                List<String> alarmCount = eventUserFeignClient.queryAlarmEvent(param1).getData();
                vo.setAlarmCount(CollectionUtil.isNotEmpty(alarmCount)?alarmCount.size():0);
                List<String> runCount = eventUserFeignClient.queryRunEvent(param1).getData();
                vo.setRunCount(CollectionUtil.isNotEmpty(runCount)?runCount.size():0);
            }

            //note 当前工程数据
            vo.setLineCount(0);
            //当前工程id
            vo.setCurrentId(id);
            //设备集合
            List<String> currentDevIds = new ArrayList<>();
            //监测点集合
            List<String> currentLineIds = new ArrayList<>();
            //获取第一层项目层级
            List<CsLedgerVO> currentProjectIds = new ArrayList<>();
            // 遍历树结构，找到匹配的工程节点
            for (CsLedgerVO engineering : appLedger) {
                if (id.equals(engineering.getId())) {
                    // 找到工程节点，获取其子节点（项目层级）
                    if (CollectionUtil.isNotEmpty(engineering.getChildren())) {
                        for (CsLedgerVO project : engineering.getChildren()) {
                            currentProjectIds.add(project);
                            // 获取项目下的设备层级
                            if (CollectionUtil.isNotEmpty(project.getChildren())) {
                                currentDevIds.addAll(project.getChildren().stream().map(CsLedgerVO::getId).collect(Collectors.toList()));
                                // 获取设备下的监测点层级
                                for (CsLedgerVO device : project.getChildren()) {
                                    if (CollectionUtil.isNotEmpty(device.getChildren())) {
                                        currentLineIds.addAll(device.getChildren().stream().map(CsLedgerVO::getId).collect(Collectors.toList()));
                                    }
                                }
                            }
                        }
                    }
                    break;
                }
            }
            //获取项目数量
            if (CollectionUtil.isNotEmpty(currentProjectIds)) {
                vo.setCurrentProjectCount(currentProjectIds.size());
            }
            //获取设备总数、在线设备、离线设备
            if (CollectionUtil.isNotEmpty(currentDevIds)) {
                List<CsEquipmentDeliveryPO> devList = csEquipmentDeliveryMapper.selectBatchIds(currentDevIds);
                //在线设备
                List<CsEquipmentDeliveryPO> onlineDevs = devList.stream().filter(dev -> Objects.equals(dev.getRunStatus(), 2)).collect(Collectors.toList());
                if (CollectionUtil.isNotEmpty(onlineDevs)) {
                    vo.setCurrentOnLineDevCount(onlineDevs.size());
                    vo.setCurrentOnLineDevs(onlineDevs);
                }
                //离线设备
                List<CsEquipmentDeliveryPO> offlineDevs = devList.stream().filter(dev -> Objects.equals(dev.getRunStatus(), 1)).collect(Collectors.toList());
                if (CollectionUtil.isNotEmpty(offlineDevs)) {
                    vo.setCurrentOffLineDevCount(offlineDevs.size());
                    vo.setCurrentOffLineDevs(offlineDevs);
                }
            }
            //获取未读事件数量
            if (CollectionUtil.isNotEmpty(currentLineIds)) {
                vo.setLineCount(currentLineIds.size());
                CsEventUserQueryParam param1 = new CsEventUserQueryParam();
                param1.setUserId(RequestUtil.getUserIndex());
                param1.setStartTime(PublicDataUtils.calculateMonthStart(time));
                param1.setEndTime(PublicDataUtils.calculateMonthEnd(time));
                param1.setEventIds(currentLineIds);

                List<String> eventCount2 = eventUserFeignClient.queryTempEvent(param1).getData();
                vo.setCurrentEventCount(CollectionUtil.isNotEmpty(eventCount2)?eventCount2.size():0);

                List<String> harmonicCount2 = eventUserFeignClient.queryTempHarmonic(param1).getData();
                vo.setCurrentHarmonicCount(CollectionUtil.isNotEmpty(harmonicCount2)?harmonicCount2.size():0);
            }
            if (CollectionUtil.isNotEmpty(currentDevIds)) {
                CsEventUserQueryParam param1 = new CsEventUserQueryParam();
                param1.setUserId(RequestUtil.getUserIndex());
                param1.setStartTime(PublicDataUtils.calculateMonthStart(time));
                param1.setEndTime(PublicDataUtils.calculateMonthEnd(time));
                param1.setEventIds(currentDevIds);

                List<String> alarmCount2 = eventUserFeignClient.queryAlarmEvent(param1).getData();
                vo.setCurrentAlarmCount(CollectionUtil.isNotEmpty(alarmCount2)?alarmCount2.size():0);

                List<String> runCount2 = eventUserFeignClient.queryRunEvent(param1).getData();
                vo.setCurrentRunCount(CollectionUtil.isNotEmpty(runCount2)?runCount2.size():0);
            }
        }
        return vo;
    }

    /**
     * 递归过滤台账树，仅保留包含目标lineId的分支
     */
    private List<CsLedgerVO> filterLedgerTree(List<CsLedgerVO> nodes, Set<String> targetLineIds) {
        if (CollectionUtils.isEmpty(nodes)) {
            return Collections.emptyList();
        }
        return nodes.stream()
                .filter(node -> isNodeRelevant(node, targetLineIds))
                .peek(node -> {
                    // 递归过滤子节点，并重新设置过滤后的子列表
                    if (CollectionUtil.isNotEmpty(node.getChildren())) {
                        node.setChildren(filterLedgerTree(node.getChildren(), targetLineIds));
                    }
                })
                .collect(Collectors.toList());
    }

    /**
     * 判断当前节点或其任意子孙节点是否包含目标lineId
     */
    private boolean isNodeRelevant(CsLedgerVO node, Set<String> targetLineIds) {
        // 1. 当前节点本身就是目标监测点
        if (node.getId() != null && targetLineIds.contains(node.getId())) {
            return true;
        }
        // 2. 子孙节点中包含目标监测点
        if (CollectionUtil.isNotEmpty(node.getChildren())) {
            return node.getChildren().stream()
                    .anyMatch(child -> isNodeRelevant(child, targetLineIds));
        }
        return false;
    }

    /** 
    * @Description: 判断当前用户是否是主用户 0-否1-是
    * @Param:  
    * @return: java.lang.String 
    * @Author: clam
    * @Date: 2023/7/25 
    */ 
    @Override
    public String isPrimaryUser(String deviceId) {
        String userIndex = RequestUtil.getUserIndex();
        List<CsDeviceUserPO> list = this.lambdaQuery().eq(CsDeviceUserPO::getDeviceId, deviceId).eq(CsDeviceUserPO::getStatus, "1").eq(CsDeviceUserPO::getPrimaryUserId, userIndex).list();
        String number = CollectionUtils.isEmpty(list) ? "0" : "1";
        return number;
    }

    @Override
    @Transactional(rollbackFor = {Exception.class})
    public Boolean transfer(List<String> ids,String useId) {
        String userIndex = useId;
        ids.forEach(eid->{
            List<CsDeviceUserPO> list = this.lambdaQuery().eq(CsDeviceUserPO::getDeviceId, eid).eq(CsDeviceUserPO::getStatus,"1" ).list();
            if(CollectionUtils.isEmpty(list)){
                throw new BusinessException(AlgorithmResponseEnum.DATA_LOSE);

            }
            this.lambdaUpdate().eq(CsDeviceUserPO::getDeviceId, eid).eq(CsDeviceUserPO::getStatus,"1" ).apply("primary_user_id=sub_user_id").set(CsDeviceUserPO::getPrimaryUserId,userIndex).set(CsDeviceUserPO::getSubUserId,userIndex).update();
            this.lambdaUpdate().eq(CsDeviceUserPO::getDeviceId, eid).eq(CsDeviceUserPO::getStatus,"1" ).apply("primary_user_id<>sub_user_id").set(CsDeviceUserPO::getPrimaryUserId,userIndex).update();

        });
        //工程人员接受到移交设备，默认把工程加入关注列表

        String role = RequestUtil.getUserRole();
        List<String> strings = JSONArray.parseArray(role, String.class);
        if(CollectionUtils.isEmpty(strings)){
            throw new BusinessException(AlgorithmResponseEnum.UNKNOW_ROLE);
        }
        List<CsLedger> list = iCsLedgerService.lambdaQuery().in(CsLedger::getId, ids).list();
        String[] split = list.get(0).getPids().split(",");
        role=strings.get(0);
        if(Objects.equals(role, AppRoleEnum.ENGINEERING_USER.getCode())){
            CsMarketData csMarketData = new CsMarketData();
            csMarketData.setEngineerId(split[1]);
            csMarketData.setUserId(RequestUtil.getUserIndex());
            QueryWrapper<CsMarketData> queryWrap = new QueryWrapper<>();
            queryWrap.setEntity(csMarketData);
            List<CsMarketData> csMarketData1 = csMarketDataMapper.selectList(queryWrap);
            if(CollectionUtils.isEmpty(csMarketData1)){
                csMarketDataMapper.insert(csMarketData);
            }

        }




        return true;
    }

    @Override
//    @Transactional(rollbackFor = {Exception.class})
    public Boolean delete(String eid) {
        String userIndex = RequestUtil.getUserIndex();
        List<CsDeviceUserPO> list = this.lambdaQuery().eq(CsDeviceUserPO::getDeviceId, eid).eq(CsDeviceUserPO::getStatus, "1").eq(CsDeviceUserPO::getPrimaryUserId, userIndex).list();
        if(CollectionUtils.isEmpty(list)){
            throw new BusinessException(AlgorithmResponseEnum.DATA_LOSE);

        }
        CsEquipmentDeliveryPO csEquipmentDeliveryPO =new CsEquipmentDeliveryPO();
        csEquipmentDeliveryPO.setId(eid);
        csEquipmentDeliveryPO.setRunStatus(0);

        csEquipmentDeliveryMapper.updateById(csEquipmentDeliveryPO);
        this.lambdaUpdate().eq(CsDeviceUserPO::getDeviceId, eid).set(CsDeviceUserPO::getStatus,"0").update();

        CsEquipmentDeliveryPO temp = csEquipmentDeliveryMapper.selectById(eid);
        mqttUserService.deleteUser(temp.getNdid());
        List<CsLedger> list1 = iCsLedgerService.lambdaQuery().eq(CsLedger::getPid, eid).list();
        if(!CollectionUtils.isEmpty(list1)){
            List<String> collect = list1.stream().map(CsLedger::getId).collect(Collectors.toList());
            LambdaQueryWrapper<CsLinePO> csLinePOLambdaQueryWrapper = new LambdaQueryWrapper<>();
            csLinePOLambdaQueryWrapper.in(CsLinePO::getLineId,collect);
            csLinePOService.remove(csLinePOLambdaQueryWrapper);
            QueryWrapper<AppLineTopologyDiagramPO> appLineTopologyDiagramPOQueryWrapper = new QueryWrapper<>();
            appLineTopologyDiagramPOQueryWrapper.clear();
            appLineTopologyDiagramPOQueryWrapper.in("line_id",collect);
            appLineTopologyDiagramService.remove(appLineTopologyDiagramPOQueryWrapper);
//            appLineTopologyDiagramService.lambdaUpdate().in(AppLineTopologyDiagramPO::getLineId,collect).set(AppLineTopologyDiagramPO::getStatus,0).update();
        }
        //删除监测点，设备
        LambdaQueryWrapper<CsLedger>  csLedgerLambdaQueryWrapper = new LambdaQueryWrapper<>();
        csLedgerLambdaQueryWrapper.clear();
        csLedgerLambdaQueryWrapper.eq(CsLedger::getId,eid);
        iCsLedgerService.remove(csLedgerLambdaQueryWrapper);
        csLedgerLambdaQueryWrapper.clear();
        csLedgerLambdaQueryWrapper.eq(CsLedger::getPid,eid);
        iCsLedgerService.remove(csLedgerLambdaQueryWrapper);
//        iCsLedgerService.lambdaUpdate().eq(CsLedger::getId,eid).set(CsLedger::getState,0).update();
//        iCsLedgerService.lambdaUpdate().eq(CsLedger::getPid,eid).set(CsLedger::getState,0).update();
        QueryWrapper<CsTouristDataPO> queryWrap = new QueryWrapper<>();
        queryWrap.eq("device_id",eid);
        csTouristDataPOService.getBaseMapper().delete(queryWrap);
        csDevModelRelationService.lambdaUpdate().eq(CsDevModelRelationPO::getDevId,eid).set(CsDevModelRelationPO::getStatus,0).update();

        return true;
    }
    /** 
    * @Description: 主用户发起取消分享，则可选择取消拥有该设备权限的子用户。子用户发起取消分享则只是移除自己拥有该设备权限
    * @Param:  
    * @return: java.lang.Boolean 
    * @Author: clam
    * @Date: 2023/7/25 
    */ 
    @Override
    @Transactional(rollbackFor = {Exception.class})
    public Boolean cancelShare(String eid,String userId) {
        String userIndex = RequestUtil.getUserIndex();
//        //主用户
//        if(Objects.equals(isPrimaryUser(eid),"1")){
//           this.lambdaUpdate().eq(CsDeviceUserPO::getDeviceId, eid).ne(CsDeviceUserPO::getSubUserId,userIndex).set(CsDeviceUserPO::getStatus,"0").update();
//        }
//        //子用户
//        else if (Objects.equals(isPrimaryUser(eid),"0")) {
            this.lambdaUpdate().eq(CsDeviceUserPO::getDeviceId, eid).eq(CsDeviceUserPO::getSubUserId,userId).set(CsDeviceUserPO::getStatus,"0").update();

//        }

        return true;
    }

    @Override
    public Boolean recovery(String eid) {
        String userIndex = RequestUtil.getUserIndex();
        List<CsDeviceUserPO> list = this.lambdaQuery().eq(CsDeviceUserPO::getDeviceId, eid).eq(CsDeviceUserPO::getStatus, "0").eq(CsDeviceUserPO::getPrimaryUserId, userIndex).list();
        if(CollectionUtils.isEmpty(list)){
            throw new BusinessException(AlgorithmResponseEnum.DATA_LOSE);

        }
        CsEquipmentDeliveryPO csEquipmentDeliveryPO =new CsEquipmentDeliveryPO();
        csEquipmentDeliveryPO.setId(eid);
        csEquipmentDeliveryPO.setRunStatus(1);
        csEquipmentDeliveryMapper.updateById(csEquipmentDeliveryPO);
        this.lambdaUpdate().eq(CsDeviceUserPO::getDeviceId, eid).set(CsDeviceUserPO::getStatus,"1").update();
        return true;
    }

    @Override
    public DevUserVO queryUserById(String devId) {
        DevUserVO devUser = new DevUserVO();
        List<CsDeviceUserPO> list = this.lambdaQuery().eq(CsDeviceUserPO::getDeviceId, devId).eq(CsDeviceUserPO::getStatus, "1").list();
        if (CollectionUtils.isEmpty(list)) {
            return devUser;
        }
        List<String> collect = list.stream().map(CsDeviceUserPO::getSubUserId).distinct().collect(Collectors.toList());
        List<User> data = userFeignClient.appuserByIdList(collect).getData();
        String primaryUserId = list.get(0).getPrimaryUserId();
        List<User> subUser = data.stream().filter(temp -> !Objects.equals(temp.getId(), primaryUserId)).collect(Collectors.toList());
        List<User> primaryUser = data.stream().filter(temp -> Objects.equals(temp.getId(), primaryUserId)).collect(Collectors.toList());
        devUser.setDevId(devId);
        devUser.setSubUsers(subUser);
        devUser.setMasterUser(primaryUser.get(0));
        return devUser;
    }

    @Override
    public List<String> findUserById(String devId) {
        List<String> result = new ArrayList<>();
        List<CsDeviceUserPO> list = this.lambdaQuery().eq(CsDeviceUserPO::getDeviceId,devId).list();
        if (CollectionUtil.isNotEmpty(list)){
            result = list.stream().map(CsDeviceUserPO::getSubUserId).collect(Collectors.toList());
        }
        //获取关注设备的用户(工程用户、营销用户)
        List<DevDetailDTO> ledger = iCsLedgerService.getInfoByIds(Collections.singletonList(devId));
        if (CollectionUtil.isNotEmpty(ledger)) {
            DevDetailDTO item = ledger.get(0);
            LambdaQueryWrapper<CsMarketData> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(CsMarketData::getEngineerId, item.getEngineeringid());
            List<CsMarketData> csMarketData = csMarketDataMapper.selectList(queryWrapper);
            if (CollectionUtil.isNotEmpty(csMarketData)) {
                List<String> collect = csMarketData.stream().map(CsMarketData::getUserId).collect(Collectors.toList());
                result.addAll(collect);
            }
        }
        if (CollectionUtil.isNotEmpty(result)) {
            result = result.stream().distinct().collect(Collectors.toList());
        }
        return result;
    }

    @Override
    public List<String> findDevByUserId(String userId) {
        List<String> result = new ArrayList<>();
        LambdaQueryWrapper<CsDeviceUserPO> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.and(wrapper ->
                wrapper.eq(CsDeviceUserPO::getPrimaryUserId, userId)
                        .or()
                        .eq(CsDeviceUserPO::getSubUserId, userId));
        List<CsDeviceUserPO> list = this.list(queryWrapper);
        if (CollectionUtil.isNotEmpty(list)){
            result = list.stream().map(CsDeviceUserPO::getDeviceId).collect(Collectors.toList());
        }
        return result;
    }

    @Override
    public void channelDevByUserId(UserDevParam param) {
        LambdaQueryWrapper<CsDeviceUserPO> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.and(wrapper ->
                wrapper.eq(CsDeviceUserPO::getPrimaryUserId, param.getUserId())
                        .or()
                        .eq(CsDeviceUserPO::getSubUserId, param.getUserId())
        ).in(CsDeviceUserPO::getDeviceId, param.getList());
        this.remove(queryWrapper);
    }

    @Override
    public List<CsDeviceUserPO> getList(UserDevParam param) {
        LambdaQueryWrapper<CsDeviceUserPO> queryWrapper = new LambdaQueryWrapper<>();
        if (StringUtils.isNotBlank(param.getUserId())) {
            queryWrapper.and(wrapper ->
                    wrapper.eq(CsDeviceUserPO::getPrimaryUserId, param.getUserId())
                            .or()
                            .eq(CsDeviceUserPO::getSubUserId, param.getUserId())
            );
        }
        if (CollectionUtil.isNotEmpty(param.getList())) {
            queryWrapper.in(CsDeviceUserPO::getDeviceId, param.getList());
        }
        queryWrapper.eq(CsDeviceUserPO::getStatus, "1");
        return this.list(queryWrapper);
    }

    /**
     *
     * @param userId 这边放设备id
     * @param list   这边放用户id集合
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean addRelation(UserDevParam param) {
        String userIndex;
        CsDeviceUserPO existingRecord = this.lambdaQuery()
                .eq(CsDeviceUserPO::getDeviceId, param.getUserId())
                .one();

        if (existingRecord != null && Objects.equals(existingRecord.getPrimaryUserId(), existingRecord.getSubUserId())) {
            userIndex = existingRecord.getPrimaryUserId();
        } else {
            userIndex = RequestUtil.getUserIndex();
            if (userIndex == null) {
                throw new IllegalArgumentException("当前用户信息获取失败");
            }

            CsDeviceUserPO mainDeviceRelation = new CsDeviceUserPO();
            mainDeviceRelation.setDeviceId(param.getUserId());
            mainDeviceRelation.setPrimaryUserId(userIndex);
            mainDeviceRelation.setSubUserId(userIndex);
            mainDeviceRelation.setStatus("1");
            boolean mainSaveSuccess = this.save(mainDeviceRelation);
            if (!mainSaveSuccess) {
                return false;
            }
        }

        if (CollectionUtil.isNotEmpty(param.getList())) {
            List<CsDeviceUserPO> batchRecords = param.getList().stream()
                    .filter(Objects::nonNull)
                    .filter(item -> !Objects.equals(item, userIndex))
                    .map(item -> {
                        CsDeviceUserPO relation = new CsDeviceUserPO();
                        relation.setDeviceId(param.getUserId());
                        relation.setPrimaryUserId(userIndex);
                        relation.setSubUserId(item);
                        relation.setStatus("1");
                        return relation;
                    })
                    .collect(Collectors.toList());

            if (!batchRecords.isEmpty()) {
                return this.saveBatch(batchRecords);
            }
        }
        return true;
    }

}
