package com.fdkankan.ucenter.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fdkankan.common.constant.SceneConstant;
import com.fdkankan.redis.util.RedisUtil;
import com.fdkankan.ucenter.common.PageInfo;
import com.fdkankan.ucenter.common.RedisKeyUtil;
import com.fdkankan.ucenter.common.SceneSourceUtil;
import com.fdkankan.ucenter.common.constants.NacosProperty;
import com.fdkankan.ucenter.common.constants.ResultCode;
import com.fdkankan.ucenter.constant.LoginConstant;
import com.fdkankan.ucenter.entity.*;
import com.fdkankan.ucenter.exception.BusinessException;
import com.fdkankan.ucenter.httpClient.service.LaserService;
import com.fdkankan.ucenter.mapper.ISceneCooperationMapper;
import com.fdkankan.ucenter.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fdkankan.ucenter.util.DateUserUtil;
import com.fdkankan.ucenter.vo.request.SceneCooperationParam;
import com.fdkankan.ucenter.vo.request.SceneParam;
import com.fdkankan.ucenter.vo.response.SceneNumVo;
import com.google.common.collect.Lists;
import com.sun.org.apache.bcel.internal.generic.RET;
import org.apache.commons.lang3.StringUtils;
import org.opencv.face.Face;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

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

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 
 * @since 2022-07-04
 */
@Service
public class SceneCooperationServiceImpl extends ServiceImpl<ISceneCooperationMapper, SceneCooperation> implements ISceneCooperationService {

    @Autowired
    ISceneProService sceneProService;
    @Autowired
    ISceneService sceneService;
    @Autowired
    IScenePlusService scenePlusService;
    @Autowired
    IScenePlusExtService scenePlusExtService;
    @Autowired
    LaserService fdkkLaserService;
    @Autowired
    ISceneResourceCooperationService sceneResourceCooperationService;
    @Autowired
    ICameraService cameraService;
    @Autowired
    ICameraDetailService cameraDetailService;
    @Autowired
    ISceneResourceService sceneResourceService;
    @Autowired
    IUserService userService;
    @Autowired
    RedisUtil redisUtil;
    @Autowired
    IMailTemplateService mailTemplateService;
    @Autowired
    IProductOrderService productOrderService;
    @Autowired
    IProductCooperationService productCooperationService;
    @Autowired
    ISceneCooperationCountService sceneCooperationCountService;

    @Override
    public Long getCooperationSceneNum(Long userId, List<Integer> sceneSourceList) {
        Long cooperationSceneProNum = this.getBaseMapper().getCooperationSceneProNum(userId, sceneSourceList);
        Long cooperationScenePlusNum = this.getBaseMapper().getCooperationScenePlusNum(userId, sceneSourceList);
        return cooperationSceneProNum + cooperationScenePlusNum;
    }

    @Override
    public List<SceneNumVo> getGroupCooperationSceneNum(Long userId) {
        List<SceneNumVo> list = this.getBaseMapper().getGroupCooperationSceneProNum(userId);
        List<SceneNumVo> list2 =this.getBaseMapper().getGroupCooperationScenePlusNum(userId);
        list.addAll(list2);
        return list;
    }

    @Override
    public void deleteCooperationList(List<ScenePro> sceneProList,List<ScenePlus> scenePlusList,List<Long> userIds) {
        if(CollectionUtils.isEmpty(sceneProList) && CollectionUtils.isEmpty(scenePlusList)){
            return;
        }
        List<String> numList = sceneProList.stream().map(ScenePro::getNum).collect(Collectors.toList());
        List<String> numList2 = scenePlusList.stream().map(ScenePlus::getNum).collect(Collectors.toList());
        numList.addAll(numList2);
        this.deleteCooperationList(numList,userIds,null);
    }

    @Override
    public void deleteCooperationList(List<String> numList,List<Long> userIds,String sceneType) {
        if(CollectionUtils.isEmpty(numList) ){
            return;
        }
        LambdaQueryWrapper<SceneCooperation> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(SceneCooperation::getSceneNum,numList);
        if(sceneType != null){
            wrapper.eq(SceneCooperation::getSceneType,sceneType);
        }
        if(userIds != null && !userIds.isEmpty()){
            wrapper.in(SceneCooperation::getUserId,userIds);
        }
        List<SceneCooperation> list = this.list(wrapper);
        List<Long> ids = list.stream().map(SceneCooperation::getId).collect(Collectors.toList());
        if(ids.size() >0){
            this.removeByIds(ids);
            sceneResourceCooperationService.deleteBatchByCooperationIds(ids);
        }
        for (String num : numList) {
            redisUtil.hdel(RedisKeyUtil.SCENE_COOPERATION_NUM_USERID,num);
        }
    }

    @Override
    public List<SceneCooperation> saveBatchByList(List<String> numList,  List<Long> userIds,String type,String sceneType) {
        List<SceneCooperation> list = new ArrayList<>();
        List<String> delList = new ArrayList<>();

        HashMap<String, List<User>> byNumList = this.getByNumList(numList,sceneType);

        for (Long userId : userIds) {
            for (String num : numList) {
                List<User> users = byNumList.get(num);
                if(users != null && !users.isEmpty()){
                    List<Long> collect1 = users.stream().map(User::getId).collect(Collectors.toList());
                    if("scene".equals(type) && numList.size() == 1){
                        for (Long l : collect1) {
                            if(!userIds.contains(l)){
                                delList.add(num + "," +l);
                            }
                        }
                    }
                    if(collect1.contains(userId)){
                        continue;
                    }
                }

                SceneCooperation sceneCooperationEntity = new SceneCooperation();
                sceneCooperationEntity.setUserId(userId);
                sceneCooperationEntity.setSceneNum(num);
                sceneCooperationEntity.setSceneType(sceneType);
                sceneCooperationEntity.setRecStatus("A");
                sceneCooperationEntity.setCreateTime(DateUserUtil.getDate(new Date()));
                sceneCooperationEntity.setUpdateTime(DateUserUtil.getDate(new Date()));
                list.add(sceneCooperationEntity);
            }
        }

        if(!list.isEmpty()){
            for (SceneCooperation sceneCooperation : list) {
                redisUtil.hset(RedisKeyUtil.SCENE_COOPERATION_NUM_USERID, sceneCooperation.getSceneNum(), sceneCooperation.getUserId() + "");
            }
            this.saveBatch(list);
        }

        for (String num : delList) {
            String[] split = num.split(",");
            delCooperation(split[0],Long.valueOf(split[1]));
        }
        return  list;
    }

    private void delCooperation(String num ,Long userId){
        redisUtil.hdel(RedisKeyUtil.SCENE_COOPERATION_NUM_USERID,num,userId.toString());
        LambdaQueryWrapper<SceneCooperation> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SceneCooperation::getSceneNum,num);
        wrapper.eq(SceneCooperation::getUserId,userId);
        this.remove(wrapper);
    }

    @Override
    public JSONObject sceneResourceList(SceneCooperationParam param) {
        JSONObject jsonObject = new JSONObject();
        List<SceneResource> exclude = new ArrayList<>();
        SceneResource excludeEntity = new SceneResource();
        excludeEntity.setKeyWord("data");
        exclude.add(excludeEntity);
        jsonObject.put("exclude", exclude);

        if(param.getCameraId() != null){
            Camera cameraEntity = cameraService.getById(param.getCameraId());
            if(cameraEntity != null){
                CameraDetail cameraDetailEntity = cameraDetailService.getByCameraId(cameraEntity.getId());
                if(cameraDetailEntity.getCompanyId() != null && cameraDetailEntity.getCompanyId() == 1){
                    jsonObject.put("exclude", new ArrayList<>());
                }
            }
        }
        List<ScenePro> sceneProList;
        List<ScenePlus> scenePlusList;

        //如果是场景协作，判断是V3的场景还是V4的场景,如果是v4场景，则查询v4的菜单资源
        if(param.getType() != null && param.getType() == 1){
            if(StringUtils.isEmpty(param.getSceneNum()) && CollectionUtils.isEmpty(param.getNumList())){
                throw new BusinessException(LoginConstant.FAILURE_CODE_3001, LoginConstant.FAILURE_MSG_3001);
            }
            List<String> numList = param.getNumList();
            if(numList == null){
                numList= new ArrayList<>();
                numList.add(param.getSceneNum());
            }
            sceneProList = sceneProService.getListByNums(numList);
            scenePlusList = scenePlusService.getListByNums(numList);
            if(CollectionUtils.isEmpty(sceneProList) && CollectionUtils.isEmpty(scenePlusList)){
                throw new BusinessException(SceneConstant.FAILURE_CODE_5005, SceneConstant.FAILURE_MSG_5005);
            }
        }else {
            //如果是相机协作，判断这个相机id下有没有V4的场景，如果有，则列出对应的菜单资源
            if(ObjectUtils.isEmpty(param.getCameraId()) && CollectionUtils.isEmpty(param.getCameraIdList())){
                throw new BusinessException(LoginConstant.FAILURE_CODE_3001, LoginConstant.FAILURE_MSG_3001);
            }
            List<Long> cameraIdList = param.getCameraIdList();
            if(cameraIdList == null){
                cameraIdList= new ArrayList<>();
                cameraIdList.add(param.getCameraId());
            }

            sceneProList = sceneProService.getListByCameraIds(cameraIdList);
            scenePlusList = scenePlusService.getListByCameraIds(cameraIdList);
        }
        List<String> versionList = Lists.newArrayList();
        if(sceneProList.size() >0){
            versionList.add("v3");
        }
        if(scenePlusList.size() >0){
            versionList.add("v4");
        }
        if(versionList.size() <=0){
            versionList.add("v3");
        }
        List<SceneResource> results = sceneResourceService.getByVersion(versionList);
        jsonObject.put("include", results);
        return jsonObject;

    }

    @Override
    public JSONObject cooperationSceneListNew(SceneParam param, String username) {
        User user = userService.getByUserName(username);
        LambdaQueryWrapper<SceneCooperation> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SceneCooperation::getUserId,user.getId());
        wrapper.eq(SceneCooperation::getSceneType,param.getIsObj() == 1?"mesh":"laser");
        List<SceneCooperation> list = this.list(wrapper);
        List<String> numList = list.parallelStream().map(SceneCooperation::getSceneNum).collect(Collectors.toList());
        if(numList.size() <=0){
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("list", new ArrayList<>());
            jsonObject.put("total",0);
            return jsonObject;
        }
        param.setNumList(numList);
        param.setHasFolder(0);
        JSONObject jsonObject = sceneProService.newList(param, username);
        return jsonObject.getJSONObject("pageInfo") ;
    }

    @Override
    public void saveCooperation(SceneCooperationParam param, String loginUserName) {
        if(StringUtils.isEmpty(param.getUserName()) || StringUtils.isEmpty(param.getSceneNum())){
            throw new BusinessException(LoginConstant.FAILURE_CODE_3001, LoginConstant.FAILURE_MSG_3001);
        }
        if(param.getUserName().equals( loginUserName)){
            throw new BusinessException(LoginConstant.FAILURE_CODE_3024, LoginConstant.FAILURE_MSG_3024);
        }
        User loginUser = userService.getByUserName(loginUserName);

        User user = userService.getByUserName(param.getUserName());
        if(user == null){
            throw new BusinessException(LoginConstant.FAILURE_CODE_3021, LoginConstant.FAILURE_MSG_3021);
        }
        String[] nums = param.getSceneNum().split(",");
        List<String> numList =  Arrays.asList(nums);
        List<ScenePro> proList = sceneProService.getListByNums(numList);
        List<ScenePlus> plusList = scenePlusService.getListByNums(numList);
        if(!"aws".equals(NacosProperty.uploadType) ){
            this.deleteCooperationList(proList,plusList,null);
        }

        saveCooperationCommon(loginUser,param.getLang(),Arrays.asList(user),proList,plusList,null,"scene",param.getSceneType());
    }

    @Override
    public ProductOrder saveBatchCooperation(SceneCooperationParam param, String loginUserName) {
        if( StringUtils.isEmpty(param.getSceneNum())){
            throw new BusinessException(LoginConstant.FAILURE_CODE_3001, LoginConstant.FAILURE_MSG_3001);
        }

        String[] nums = param.getSceneNum().split(",");
        List<String> numList =  Arrays.asList(nums);

        if(param.getUserNameList() == null || param.getUserNameList().isEmpty()){
            this.deleteCooperationList(numList,null,param.getSceneType());
            if("laser".equals(param.getSceneType())){
                laserService.saveBatchCooperation(numList,new ArrayList<>(),param.getUserNameList(),"scene","update");
            }
            return null;
        }
        if(param.getUserNameList().contains( loginUserName)){
            throw new BusinessException(LoginConstant.FAILURE_CODE_3024, LoginConstant.FAILURE_MSG_3024);
        }
        if(param.getUserNameList().size() != new HashSet<>(param.getUserNameList()).size()){
            throw new BusinessException(ResultCode.COO_LIMIT_ERROR2);
        }
        if(param.getUserNameList().size() >5){
            throw new BusinessException(ResultCode.COO_LIMIT_ERROR);
        }
        User loginUser = userService.getByUserName(loginUserName);
        if(numList.size() >1){
            HashMap<String, List<User>> byNumList = this.getByNumList(numList, param.getSceneType());
            for (String num : numList) {
                if(byNumList.get(num) != null && !byNumList.isEmpty()) {
                    if (byNumList.get(num).size() + param.getUserNameList().size() > 5) {
                        throw new BusinessException(ResultCode.COO_LIMIT_ERROR);
                    }
                    List<User> users = byNumList.get(num);
                    Set<String> collect = users.stream().map(User::getUserName).collect(Collectors.toSet());

                    if(collect.containsAll(param.getUserNameList())){
                        throw new BusinessException(ResultCode.COO_LIMIT_ERROR2);
                    }
                }
            }
        }

        List<User> users = new ArrayList<>();
        for (String userName : param.getUserNameList()) {
            User user = userService.getByUserName(userName);
            if(user == null){
                throw new BusinessException(LoginConstant.FAILURE_CODE_3021, LoginConstant.FAILURE_MSG_3021);
            }
            users.add(user);
        }


        ProductOrder productOrder = checkNeedPay(numList, users, loginUser, param.getPayType(), param.getTimeZone(),null,param.getLang(),param.getSceneType());

        if(productOrder == null){
            successAddCooperation(numList,users,param.getLang(),loginUser,param.getSceneType());
        }
        return productOrder;

    }

    @Override
    public ProductOrder saveCamera(SceneCooperationParam param, String loginUserName) {
        if(param.getCameraId() == null  || StringUtils.isEmpty(param.getUserName())){
            throw new BusinessException(LoginConstant.FAILURE_CODE_3001, LoginConstant.FAILURE_MSG_3001);
        }
        if(param.getUserName().equals( loginUserName)){
            throw new BusinessException(LoginConstant.FAILURE_CODE_3025, LoginConstant.FAILURE_MSG_3025);
        }
        User user = userService.getByUserName(param.getUserName());
        if(user == null){
            throw new BusinessException(LoginConstant.FAILURE_CODE_3015,LoginConstant.FAILURE_MSG_3015);
        }
        User loginUser = userService.getByUserName(loginUserName);
        Camera camera = cameraService.getById(param.getCameraId());
        CameraDetail cameraDetail = cameraDetailService.getByCameraId(param.getCameraId());
        if(camera == null || cameraDetail == null || cameraDetail.getUserId() == null){
            throw new BusinessException(ResultCode.CAMERA_NOT_EXIT);
        }
        if(!loginUser.getId().equals(cameraDetail.getUserId())){
            throw new BusinessException(ResultCode.NOT_PER);
        }
        if(cameraDetail.getCooperationUser() != null){
            throw new BusinessException(ResultCode.COO_ERROR);
        }

        List<ScenePro> v3List = sceneProService.getListByCameraId(param.getCameraId());
        List<ScenePlus> v4List = scenePlusService.getListByCameraId(param.getCameraId());
        List<String> v3NumList = v3List.stream().map(ScenePro::getNum).collect(Collectors.toList());
        List<String> v4NumList = v4List.stream().map(ScenePlus::getNum).collect(Collectors.toList());

        List<String> allList = new ArrayList<>();
        allList.addAll(v3NumList);
        allList.addAll(v4NumList);

        ProductOrder productOrder = checkNeedPay(allList, Arrays.asList(user), loginUser, param.getPayType(), param.getTimeZone(),param.getCameraId(),param.getLang(),null);
        if(productOrder == null){
            successAddCooperation(v3List,v4List,Arrays.asList(user),param.getLang(),loginUser,Arrays.asList(camera),null);
            cameraDetailService.updateCooperationByIds(Arrays.asList(param.getCameraId()),user.getId());
        }

        return productOrder;
    }

    private void  successAddCooperation(List<String> numList, List<User> users, String lang, User loginUser,String sceneType){
        List<ScenePro> proList = sceneProService.getListByNums(numList);
        List<ScenePlus> plusList = scenePlusService.getListByNums(numList);
        List<Long> userIds = users.stream().map(User::getId).collect(Collectors.toList());
        //this.deleteCooperationList(proList,plusList,userIds);

        saveCooperationCommon(loginUser,lang,users,proList,plusList,null,"scene",sceneType);
    }

    @Override
    public void  successAddCooperation(List<String> numList,List<Long> userIds,Long loginUserId,Long cameraId,String lang,String sceneType,List<ProductCooperation> needPay ){
        //this.deleteCooperationList(numList,userIds);
        List<ScenePro> proList = sceneProService.getListByNums(numList);
        List<ScenePlus> plusList = scenePlusService.getListByNums(numList);
        List<User> users = userService.listByIds(userIds);
        User user = userService.getById(loginUserId);
        if(cameraId != null ){
            Camera camera = cameraService.getById(cameraId);
            saveCooperationCommon(user,lang,users,proList,plusList,Arrays.asList(camera),"camera",sceneType);
            cameraDetailService.updateCooperationByIds(Arrays.asList(cameraId),userIds.get(0));
        }else {
            saveCooperationCommon(user,lang,users,proList,plusList,null,"scene",sceneType);
        }
        sceneCooperationCountService.saveCount(needPay,userIds.size());

    }

    private void  successAddCooperation(List<ScenePro> v3List,List<ScenePlus> v4List,List<User> users,String lang,User loginUser,List<Camera>cameraList,String sceneType){
        List<Long> userIds = users.stream().map(User::getId).collect(Collectors.toList());
        //this.deleteCooperationList(v3List,v4List,userIds);
        saveCooperationCommon(loginUser,lang,users,v3List,v4List,cameraList,"camera",sceneType);

    }



    private ProductOrder checkNeedPay(List<String> numList, List<User> users,User loginUser,Integer payType,Integer timeZone,Long cameraId,String lang,String sceneType) {
        HashMap<String,String> needNumListMesh = new HashMap<>();
        HashMap<String,String> needNumListLaser =new HashMap<>();
        if(StringUtils.isBlank(sceneType)){
            needNumListMesh = getTotalCount(numList,users,"mesh",cameraId);
            needNumListLaser =  getTotalCount(numList,users,"laser",cameraId);
        }else {
            needNumListMesh = getTotalCount(numList,users,sceneType,cameraId);
        }
        if(needNumListMesh.size() + needNumListLaser.size()<=0){
            return null;
        }
        ProductOrder productOrder = productOrderService.createOrder(needNumListMesh.size() + needNumListLaser.size(), "cooperation", loginUser, payType, timeZone, cameraId, lang, sceneType);
        productCooperationService.add(productOrder,users,numList,needNumListMesh,needNumListLaser,sceneType);
        return productOrder;

    }

    private HashMap<String,String> getTotalCount(List<String> numList, List<User> users,String sceneType,Long cameraId){
        List<String> forList = new ArrayList<>(numList);

        List<SceneCooperationCount> freeCountList = sceneCooperationCountService.getByNumList(numList,sceneType);
        HashMap<String,Integer> freeMap = new HashMap<>();
        freeCountList.forEach(e -> freeMap.put(e.getNum(),e.getCount()));
        HashMap<String, List<User>> map = this.getByNumList(numList,sceneType);
        HashMap<String,String> needNumList = new HashMap<>();

        if(cameraId != null && "mesh".equals(sceneType)){
            CameraDetail cameraDetail = cameraDetailService.getByCameraId(cameraId);
            if(cameraDetail == null || cameraDetail.getType() == null){
                throw new BusinessException(ResultCode.CAMERA_NOT_EXIT);
            }
            if(cameraDetail.getType() == 10 || cameraDetail.getType() == 11){
                List<ScenePro> listByNums = sceneProService.getListByNums(numList);
                List<String> newList = listByNums.stream().filter(e->e.getIsObj() == 1).map(ScenePro::getNum).collect(Collectors.toList());

                List<ScenePlus> listByNums1 = scenePlusService.getListByNums(numList);
                List<Long> ids = listByNums1.stream().map(ScenePlus::getId).collect(Collectors.toList());
                HashMap<Long, ScenePlusExt> byPlusIds = scenePlusExtService.getByPlusIds(ids);
                List<String> newList2 = listByNums1.stream().filter(e -> byPlusIds.get(e.getId()) != null && byPlusIds.get(e.getId()).getIsObj() == 1).map(ScenePlus::getNum).collect(Collectors.toList());
                forList = newList;
                forList.addAll(newList2);
            }
        }

        for (String num : forList) {
            Integer freeCount = freeMap.get(num) == null ? 1 :freeMap.get(num);

            List<User> dbUserList = map.get(num);

            if(dbUserList != null && !dbUserList.isEmpty()){
                List<Long> dbUserIds = dbUserList.stream().map(User::getId).collect(Collectors.toList());
                HashMap<Long,User> userHashMap = new HashMap<>();
                for (User user : users) {
                    if(dbUserIds.contains(user.getId())){
                        userHashMap.put(user.getId(),user);
                    }
                }
                Integer totalSize = dbUserList.size() - userHashMap.size();

                if(numList.size() >1 || cameraId != null){
                    freeCount = (totalSize > freeCount ? totalSize :  (freeCount - totalSize));
                }else {
                    freeCount = (totalSize > freeCount ? totalSize : freeCount) ;
                }
            }

            for (int i = 0 ; i< users.size() - freeCount;i++){
                needNumList.put(users.get(i).getId()+","+num,num);
            }

        }
        return needNumList;
    }

    @Autowired
    LaserService laserService;

    private void saveCooperationCommon(User LoginUser,String lang,List<User> userList,List<ScenePro> proList, List<ScenePlus> plusList,List<Camera >cameraList,String type,String sceneType){

        List<Long> userIds = userList.stream().map(User::getId).collect(Collectors.toList());
        Set<String> numList = new HashSet<>();
        List<String> v3List = proList.stream().map(ScenePro::getNum).collect(Collectors.toList());
        List<String> v4List = plusList.stream().map(ScenePlus::getNum).collect(Collectors.toList());
        numList.addAll(v3List);
        numList.addAll(v4List);

        List<ScenePro> collect1 = proList.stream().filter(e -> SceneSourceUtil.getLaserList().contains(e.getSceneSource())).collect(Collectors.toList());
        List<ScenePlus> collect2 = plusList.stream().filter(e -> SceneSourceUtil.getLaserList().contains(e.getSceneSource())).collect(Collectors.toList());
        Set<String> numList1 = collect1.stream().map(ScenePro::getNum).collect(Collectors.toSet());
        Set<String> numList2 = collect2.stream().map(ScenePlus::getNum).collect(Collectors.toSet());
        numList1.addAll(numList2);


        if(StringUtils.isBlank(sceneType) && ( !collect1.isEmpty() || !collect2.isEmpty())){
            List<String> newList = collect1.stream().filter(e->e.getIsObj() == 1).map(ScenePro::getNum).collect(Collectors.toList());
            List<Long> ids = collect2.stream().map(ScenePlus::getId).collect(Collectors.toList());
            HashMap<Long, ScenePlusExt> byPlusIds = scenePlusExtService.getByPlusIds(ids);
            List<String> newList2 = collect2.stream().filter(e -> byPlusIds.get(e.getId()) != null && byPlusIds.get(e.getId()).getIsObj() == 1).map(ScenePlus::getNum).collect(Collectors.toList());
            numList = new HashSet<>();
            numList.addAll(newList2);
            numList.addAll(newList);
        }


        List<SceneCooperation> addList =new ArrayList<>();
        if(StringUtils.isNotBlank(sceneType) ){
            if(!numList.isEmpty() && "mesh".equals(sceneType)){
                addList = this.saveBatchByList(new ArrayList<>(numList), userIds, type,"mesh");
            }
            if(!numList1.isEmpty() && "laser".equals(sceneType)){
                addList = this.saveBatchByList(new ArrayList<>(numList1), userIds, type,"laser");
            }
        }else {
            if(!numList.isEmpty()){
                addList = this.saveBatchByList(new ArrayList<>(numList), userIds, type,"mesh");
            }
            if(!numList1.isEmpty() ){
                addList = this.saveBatchByList(new ArrayList<>(numList1), userIds, type,"laser");
            }
        }

        List<Long> collect3 = addList.stream().map(SceneCooperation::getUserId).collect(Collectors.toList());
        for (User user : userList) {
            if("aws".equals(NacosProperty.uploadType)){
                if("camera".equals(type) && cameraList != null){
                    HashMap<Long, Camera> cameraMap = new HashMap<>();
                    cameraList.forEach(e -> cameraMap.put(e.getId(),e));
                    mailTemplateService.sendCameraCooperation(cameraMap,user.getUserName(),lang);
                }else {
                    if(collect3.contains(user.getId())){
                        mailTemplateService.sendSceneCooperation(proList,plusList,user.getUserName(),lang);
                    }
                }
            }
        }


        List<String> collect = userList.stream().map(User::getUserName).collect(Collectors.toList());
        List<String> snCodeList = new ArrayList<>();
        if(cameraList !=null ){
            snCodeList = cameraList.stream().map(Camera::getSnCode).collect(Collectors.toList());
        }
        if(StringUtils.isNotBlank(sceneType) && "mesh".equals(sceneType)){
            return;
        }
        String operatingMode = (StringUtils.isBlank(sceneType) || numList1.size() > 1) ? "add" :"update";
        laserService.saveBatchCooperation(new ArrayList<>(numList1),snCodeList,collect,type,operatingMode);

    }

    @Override
    public void deleteCooperation(SceneCooperationParam param, String username) {
        if(StringUtils.isEmpty(param.getSceneNum())){
            throw new BusinessException(LoginConstant.FAILURE_CODE_3001, LoginConstant.FAILURE_MSG_3001);
        }
        String[] nums = param.getSceneNum().split(",");
        List<String> numList =  Arrays.asList(nums);
        List<ScenePro> proList = sceneProService.getListByNums(numList);
        List<ScenePlus> plusList = scenePlusService.getListByNums(numList);
        this.deleteCooperationList(proList,plusList,null);
    }

    @Override
    public List<SceneResource> getResourceByNum(String sceneNum) {
        if(StringUtils.isEmpty(sceneNum)){
            throw new BusinessException(LoginConstant.FAILURE_CODE_3001, LoginConstant.FAILURE_MSG_3001);
        }
        LambdaQueryWrapper<SceneCooperation> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SceneCooperation::getSceneNum,sceneNum);
        List<SceneCooperation> list = this.list(wrapper);
        if(list == null || list.size()<=0){
            return new ArrayList<>();
        }
        return sceneResourceService.getByCooperationId(list.get(0).getId());
    }

    @Override
    public List<String> getNumByUserIds(List<Long> userIds) {
        LambdaQueryWrapper<SceneCooperation> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(SceneCooperation::getUserId,userIds);
        Set<String> collect = this.list(wrapper).parallelStream().map(SceneCooperation::getSceneNum).collect(Collectors.toSet());
        return new ArrayList<>(collect);
    }

    @Override
    public HashMap<String, List<User>> getByNumList(List<String> numList,String sceneType) {
        if(numList == null || numList.isEmpty()){
            return new HashMap<>();
        }
        LambdaQueryWrapper<SceneCooperation> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(SceneCooperation::getSceneNum,numList);
        if(StringUtils.isNotBlank(sceneType)){
            wrapper.eq(SceneCooperation::getSceneType,sceneType);
        }
        List<SceneCooperation> list = this.list(wrapper);
        HashMap<String,List<User>> cooMap = new HashMap<>();
        if(list.size() >0){
            List<Long> userIds = list.parallelStream().map(SceneCooperation::getUserId).collect(Collectors.toList());
            if(userIds.size() >0){
                HashMap<Long, User> userMap = userService.getByIds(userIds);
                for (SceneCooperation entity : list) {
                    User user = userMap.get(entity.getUserId());
                    cooMap.computeIfAbsent(entity.getSceneNum(), k -> new ArrayList<>());
                    if(!cooMap.get(entity.getSceneNum()).contains(user)){
                        cooMap.get(entity.getSceneNum()).add(user);
                    }
                }
            }
        }
        return cooMap;
    }

    @Override
    public List<SceneCooperation> getByNum(String num,String sceneType) {
        LambdaQueryWrapper<SceneCooperation> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SceneCooperation::getSceneNum,num);
        wrapper.eq(SceneCooperation::getSceneType,sceneType);
        List<SceneCooperation> list = this.list(wrapper);
        return list;
    }

    @Override
    public Object cooperationSceneList(SceneParam param, String username) {
        return null;
    }


    @Override
    public void saveByRegister(User register, String registerCooperationNum, String sceneType) {
        if(StringUtils.isNotBlank(registerCooperationNum)){
            List<SceneCooperation> list = new ArrayList<>();
            String[] split = registerCooperationNum.split(",");
            for (String num : split) {
                SceneCooperation sceneCooperation = new SceneCooperation();
                sceneCooperation.setSceneNum(num);
                sceneCooperation.setUserId(register.getId());
                sceneCooperation.setSceneType(sceneType);
                list.add(sceneCooperation);

            }
            if(!list.isEmpty()){
                this.saveBatch(list);
            }
            if("laser".equals(sceneType)){
                List<String> collect = list.stream().map(SceneCooperation::getSceneNum).collect(Collectors.toList());
                laserService.saveBatchCooperation(collect,new ArrayList<>(),Arrays.asList(register.getUserName()),"scene","add");

            }
        }
    }
}
