package com.fdkankan.scene.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.csp.sentinel.util.StringUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fdkankan.common.constant.TbStatus;
import com.fdkankan.common.response.ResultData;
import com.fdkankan.common.user.SSOLoginHelper;
import com.fdkankan.common.util.PageInfoUtils;
import com.fdkankan.platform.api.dto.Camera;
import com.fdkankan.platform.api.feign.PlatformGoodsClient;
import com.fdkankan.scene.entity.*;
import com.fdkankan.scene.mapper.ISceneCooperationMapper;
import com.fdkankan.scene.mapper.ISceneProMapper;
import com.fdkankan.scene.service.*;
import com.fdkankan.scene.util.ParamConvertUtil;
import com.fdkankan.scene.vo.SceneCooperationParamVO;
import com.fdkankan.scene.vo.SceneParamVO;
import com.fdkankan.scene.vo.SceneVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author dengsixing
 * @since 2021-12-23
 */
@Service
public class SceneCooperationServiceImpl extends ServiceImpl<ISceneCooperationMapper, SceneCooperation> implements ISceneCooperationService {

    @Autowired
    SSOLoginHelper ssoLoginHelper;
    @Autowired
    PlatformGoodsClient platformGoodsClient;
    @Autowired
    ISceneProService sceneProService;
    @Autowired
    ISceneResourceService sceneResourceService;
    @Autowired
    ISceneProMapper sceneProMapper;
    @Autowired
    IFolderService folderService;
    @Autowired
    IFolderSceneService folderSceneService;
    @Autowired
    ISceneService sceneService;
    @Autowired
    ISceneEditInfoExtService sceneEditInfoExtService;
    @Autowired
    ISceneResourceCooperationService sceneResourceCooperationService;
    @Autowired
    ISceneCooperationMapper sceneCooperationMapper;

    @Override
    public void updateRecStatus(String sceneNum) {
        this.update(new LambdaUpdateWrapper<SceneCooperation>()
                .eq(SceneCooperation::getNum, sceneNum)
                .set(SceneCooperation::getUpdateTime, Calendar.getInstance().getTime())
                .set(SceneCooperation::getTbStatus, TbStatus.DELETE.code()));
    }

    @Override
    public String findUserName(String sceneNum) {

        SceneCooperation sceneCooperation = this.findBySceneNum(sceneNum);
        if(Objects.isNull(sceneCooperation)) return null;

        return sceneCooperation.getUserName();
    }

    @Override
    public SceneCooperation findBySceneNum(String sceneNum) {
        List<SceneCooperation> list = this.list(new LambdaQueryWrapper<SceneCooperation>()
                .eq(SceneCooperation::getTbStatus, TbStatus.VALID.code())
                .eq(SceneCooperation::getNum, sceneNum)
                .orderByDesc(SceneCooperation::getId));
        if(CollUtil.isEmpty(list)){
            return null;
        }
        return list.get(0);
    }

    @Override
    public ResultData sceneResourceBySceneNum(SceneCooperationParamVO param) throws Exception{

        ResultData<Camera> cameraResult = platformGoodsClient.getCameraByChildName(param.getUserName());
        Camera camera = cameraResult.getData();
        if(camera != null){
            return ResultData.ok();
        }

        SceneCooperation sceneCooperation = this.findBySceneNum(param.getNum());
        //若数据为空表示可操作全部资源
        if(sceneCooperation == null || !sceneCooperation.getUserId().equals(param.getUserId())){
            return ResultData.ok();
        }

        ScenePro scenePro= sceneProService.findBySceneNum(param.getNum());
        if(scenePro != null && scenePro.getUserId().equals(sceneCooperation.getUserId())){
            return ResultData.ok();
        }

        return ResultData.ok(sceneResourceService.findByCooperationId(sceneCooperation.getId()));
    }

    @Override
    public List<SceneCooperation> getListByUserId(List<Long> userIds) {
        LambdaQueryWrapper<SceneCooperation> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(SceneCooperation::getUserId,userIds);
        return this.list(queryWrapper);
    }

    @Override
    public Page cooperationSceneListNew(SceneParamVO param) throws Exception{

        //查询该用户所有的协作场景
        List<SceneCooperation> list = this.list(
            new LambdaQueryWrapper<SceneCooperation>()
                .select(SceneCooperation::getNum)
                .eq(SceneCooperation::getUserId, param.getUserId())
                .orderByDesc(SceneCooperation::getId));
        if(CollUtil.isEmpty(list)){
            return new Page(param.getPageNum(), param.getPageSize());
        }


        //获取所有协作场景的场景码集合
        List<String> sceneNumList = new ArrayList<>();
        for(SceneCooperation cooperation: list){
            if(Objects.isNull(cooperation.getNum())){
                continue;
            }
            sceneNumList.add(cooperation.getNum());
        }

        if(sceneNumList.size() <= 0){
            return new Page(param.getPageNum(), param.getPageSize());
        }

        List<Object> result = new ArrayList<>();
        List<SceneProPO> sceneList = new ArrayList<>();
        List<Folder> folderList = new ArrayList<>();

        if(StringUtil.isNotBlank(param.getSceneSource())){
            param.setSceneSourceList(ParamConvertUtil.getSceneSource(param.getSceneSource()));
        }

        //根目录时，需要排除已经归类的场景
        if(ObjectUtils.isEmpty(param.getFolderId())){
            sceneList = sceneProMapper.selectCooperationSceneList(param);

        }else {
            //获取文件夹数量
            folderList= folderService.list(
                new LambdaQueryWrapper<Folder>().eq(Folder::getUserId, param.getUserId())
                    .eq(Folder::getParentId, param.getFolderId())
                    .orderByDesc(Folder::getId));

            //进入目录层级后，根据目录获取当前目录的所有场景
            List<Long> sceneIdList = folderSceneService
                .getSceneIdListByFolderId(param.getFolderId());

            if(CollUtil.isNotEmpty(sceneIdList)){
                param.setSceneIdList(sceneIdList);
                sceneList = sceneProMapper.selectCooperationSceneList(param);
            }
        }
        List<SceneVO> responseScenes = sceneService.convertPro(sceneList);

        if(Objects.isNull(param.getSceneSource())&& StrUtil.isEmpty(param.getSceneType()) &&
                param.getStartTime() == null && param.getEndTime() == null){

            result.addAll(folderService.convert(folderList));
        }

        result.addAll(responseScenes);

        Page<Object> page  = PageInfoUtils.list2PageInfo(result, param.getPageNum(), param.getPageSize());
        if(CollUtil.isEmpty(page.getRecords())){
            return new Page(param.getPageNum(), param.getPageSize());
        }
        page.getRecords().parallelStream().filter(object -> object instanceof SceneVO).forEach(object -> {
            SceneVO responseScene = (SceneVO) object;
            if (responseScene.getCameraId() != null) {
                ResultData<Camera> cameraResult = platformGoodsClient
                    .getCameraById(responseScene.getCameraId());
                Camera camera = cameraResult.getData();
                if (camera != null) {
                    responseScene.setChildName(camera.getChildName());
                    responseScene.setSnCode(camera.getSnCode());
                }
            }
            // 获取VrThumb
            SceneEditInfoExt sceneEditInfoExt = sceneEditInfoExtService.getOne(
                new LambdaQueryWrapper<SceneEditInfoExt>()
                    .select(SceneEditInfoExt::getVrNum)
                    .eq(SceneEditInfoExt::getSceneProId, responseScene.getId()));
            if (Objects.nonNull(sceneEditInfoExt)) {
                responseScene.setVrNum(sceneEditInfoExt.getVrNum());
            }
        });
        return page;
    }

    @Override
    public List<SceneCooperation> getListByNums(List<String> numList) {
        return this.list(new LambdaQueryWrapper<SceneCooperation>().in(SceneCooperation::getNum,numList));
    }

    @Override
    public void updateRecStatusList(List<Long> ids) {
        this.update(new LambdaUpdateWrapper<SceneCooperation>()
                .set(SceneCooperation::getTbStatus,TbStatus.DELETE.code())
                .in(SceneCooperation::getId,ids));
    }

    @Override
    public void saveByResourceIds(List<SceneProPO> sceneProList, Long cameraId, String resourceIds,Long userId) {
        List<SceneResourceCooperation> sceneResourceCooperationEntityList = new ArrayList<>();

        for (SceneProPO sceneProEntity : sceneProList) {
            //保存相机下新的场景关联关系
            SceneCooperation sceneCooperationEntity = new SceneCooperation();
            sceneCooperationEntity.setUserId(userId);
            sceneCooperationEntity.setNum(sceneProEntity.getNum());
            this.save(sceneCooperationEntity);

            if(StringUtil.isNotEmpty(resourceIds)){
                SceneResourceCooperation sceneResourceCooperationEntity = null;
                String[] ids = resourceIds.split(",");
                for(String resourceId : ids){
                    sceneResourceCooperationEntity = new SceneResourceCooperation();
                    sceneResourceCooperationEntity.setSceneResourceId(Long.valueOf(resourceId));
                    sceneResourceCooperationEntity.setSceneCooperationId(sceneCooperationEntity.getId());
                    sceneResourceCooperationEntityList.add(sceneResourceCooperationEntity);
                }
            }
        }
        if(sceneResourceCooperationEntityList.size()>0){
            sceneResourceCooperationService.saveBatch(sceneResourceCooperationEntityList);
        }
    }

    @Override
    public Integer getCooperationSceneNum(Long userId, List<Integer> sceneSourceList) {
        return sceneCooperationMapper.getCooperationSceneNum(userId,sceneSourceList);
    }
}
