package com.yida.data.device.camera.service.impl;

import cc.mrbird.febs.common.redis.service.RedisService;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.injector.AbstractMethod;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yida.data.common.core.entity.camera.*;
import com.yida.data.common.core.entity.camera.enums.CommonTypeEnum;
import com.yida.data.common.core.entity.camera.enums.ThemeTypeEnum;
import com.yida.data.common.core.entity.constant.CachePrefixConstant;
import com.yida.data.common.core.entity.user.EduStaff;
import com.yida.data.common.core.entity.user.EduStaffDept;
import com.yida.data.common.core.entity.user.EduStudent;
import com.yida.data.device.camera.mapper.EduCameraAreaGroupMapper;
import com.yida.data.device.camera.mapper.EduCameraMapper;
import com.yida.data.device.camera.mapper.EduCameraStrategyThemeMapper;
import com.yida.data.device.camera.service.*;
import com.yida.data.device.camera.util.RecordVideoStream;
import com.yida.data.device.vo.camera.EduCameraAreaGroupVO;
import com.yida.data.device.vo.camera.H5ThemeListVO;
import com.yida.data.device.vo.camera.ListCameraVO;
import com.yida.data.user.feign.RemoteStaffService;
import com.yida.data.user.feign.RemoteStudentService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author ccl
 */
@Slf4j
@Service
@RequiredArgsConstructor
@Transactional(rollbackFor = Exception.class)
public class EduCameraAreaGroupServiceImpl extends ServiceImpl
    <EduCameraAreaGroupMapper, EduCameraAreaGroup> implements EduCameraAreaGroupService {

    private final RemoteStaffService staffService;
    private final EduCameraAreaGroupCameraService groupCameraService;
    private final EduCameraMapper cameraMapper;
    private final RemoteStudentService studentService;
    private final EduCameraStrategyOpenClassService classService;
    private final EduCameraStrategyThemeMapper themeMapper;
    private final EduCameraStrategyOpenTimeService timeService;
    private final EduCameraStrategyOpenCameraService openCameraService;
    private final RecordVideoStream videoStream;
    private final RedisService redisService;

    /**
     * @param schoolId
     * @return 分组列表
     */
    @Override
    public List<EduCameraAreaGroup> listCameraGroup(Long schoolId) {
        return list(Wrappers.query(new EduCameraAreaGroup()).lambda().eq(EduCameraAreaGroup::getSchoolId, schoolId));
    }

    /**
     * 查询分组对应所有设备
     *
     * @param page
     * @param groupId
     * @return
     */
    @Override
    public Page<EduCamera> listCamera(Page<EduCamera> page, Long groupId, String cameraCode, Long staffId) {

        EduStaff data = staffService.getStaff(staffId).getData();
        if (ObjectUtil.isEmpty(data)) {
            return new Page<>();
        }
        List<EduStaffDept> staffDept = data.getStaffDept();
        List<Long> deptId = new ArrayList<>();
        for (EduStaffDept eduStaffDept : staffDept) {
            deptId.add(eduStaffDept.getDeptId());
        }
        Page<EduCamera> cameraPage = baseMapper.listCamera(page, groupId, cameraCode, data.getId(), deptId);
        for (EduCamera record : cameraPage.getRecords()) {
            //取图，并传媒资
            if (redisService.hHasKey(record.getId().toString(), CachePrefixConstant.EDU_CAMERA)) {
                String url = (String) redisService.hget(record.getId().toString(), CachePrefixConstant.EDU_CAMERA);
                record.setFirstImg(url);
            } else {
                String firstPicByStream = videoStream.getFirstPicByStream(record.getTransUrl());
                record.setFirstImg(firstPicByStream);
                redisService.hset(record.getId().toString(), CachePrefixConstant.EDU_CAMERA, firstPicByStream, 300L);
            }

        }
        return cameraPage;
    }

    @Override
    public List<EduCameraAreaGroup> findAreaGroupList(Long schoolId) {

        //第一级节点
        List<EduCameraAreaGroup> parentList = baseMapper.findAreaGroupList(schoolId, null);
        for (EduCameraAreaGroup areaGroup : parentList) {
            //第二级节点
            List<EduCameraAreaGroup> areaGroupList = baseMapper.findAreaGroupList(schoolId, areaGroup.getId());
            areaGroup.setAreaGroupList(areaGroupList);
            for (EduCameraAreaGroup eduCameraAreaGroup : areaGroupList) {
                //第三级节点
                List<EduCameraAreaGroup> areaGroupList1 = baseMapper.findAreaGroupList(schoolId, eduCameraAreaGroup.getId());
                eduCameraAreaGroup.setAreaGroupList(areaGroupList1);
            }
        }

        return parentList;
    }

    @Override
    public List<EduCamera> findGroupCamera(Long id) {
        List<EduCameraAreaGroupCamera> listCamera = groupCameraService
            .list(Wrappers.query(new EduCameraAreaGroupCamera()).lambda().eq(EduCameraAreaGroupCamera::getGroupId, id));

        List<Long> cameraIdList = new ArrayList<>();
        for (EduCameraAreaGroupCamera eduCameraAreaGroupCamera : listCamera) {
            cameraIdList.add(eduCameraAreaGroupCamera.getCameraId());
        }
        if (CollectionUtil.isNotEmpty(cameraIdList)) {
            return cameraMapper.selectBatchIds(cameraIdList);
        }
        return new ArrayList<>();
    }

    @Override
    public void updateAreaGroupList(String name, Integer upOrDown, Long groupId) {
        EduCameraAreaGroup byId = getById(groupId);
        if (ObjectUtil.isNotEmpty(name) && upOrDown == null) {

            byId.setName(name);
            updateById(byId);
            return;
        }
        //0上1下
        if (upOrDown == 0) {
            Long parentId = byId.getParentId();
            List<EduCameraAreaGroup> groupList = baseMapper.findGroup(parentId);
            for (int i = 0; i < groupList.size(); i++) {
                if (groupList.get(i).getId().equals(groupId) && groupList.size() > 1 && i > 0) {
                    EduCameraAreaGroup areaGroup = groupList.get(i);
                    EduCameraAreaGroup areaGroup1 = groupList.get(i - 1);
                    Integer sort = areaGroup.getSort();
                    Integer sort1 = areaGroup1.getSort();
                    areaGroup.setSort(sort1);
                    areaGroup1.setSort(sort);
                    List<EduCameraAreaGroup> list = new ArrayList<>();
                    list.add(areaGroup);
                    list.add(areaGroup1);
                    saveOrUpdateBatch(list);
                }
            }
        } else if (upOrDown == 1) {
            Long parentId = byId.getParentId();
            List<EduCameraAreaGroup> groupList = baseMapper.findGroup(parentId);
            for (int i = 0; i < groupList.size(); i++) {
                if ((groupList.get(i).getId().equals(groupId)) && (i < (groupList.size() - 1))) {
                    EduCameraAreaGroup areaGroup = groupList.get(i);
                    EduCameraAreaGroup areaGroup1 = groupList.get(i + 1);
                    Integer sort = areaGroup.getSort();
                    Integer sort1 = areaGroup1.getSort();
                    areaGroup.setSort(sort1);
                    areaGroup1.setSort(sort);
                    List<EduCameraAreaGroup> list = new ArrayList<>();
                    list.add(areaGroup);
                    list.add(areaGroup1);
                    saveOrUpdateBatch(list);
                }
            }
        }
    }

    @Override
    public List<EduCameraAreaGroupVO> findTreeGroup(Long schoolId) {
        //第一级节点
        List<EduCameraAreaGroupVO> parentList = baseMapper.findTreeGroup(schoolId, null);
        for (EduCameraAreaGroupVO areaGroup : parentList) {
            areaGroup.setLevel(1);
            //第二级节点
            List<EduCameraAreaGroupVO> areaGroupList = baseMapper.findTreeGroup(schoolId, areaGroup.getId());
            if (CollectionUtil.isNotEmpty(areaGroupList)) {
                for (EduCameraAreaGroupVO eduCameraAreaGroup : areaGroupList) {
                    //第三级节点
                    eduCameraAreaGroup.setLevel(2);
                    List<EduCameraAreaGroupVO> areaGroupList1 = baseMapper.findTreeGroup(schoolId, eduCameraAreaGroup.getId());
                    if (CollectionUtil.isNotEmpty(areaGroupList1)) {
                        for (EduCameraAreaGroupVO three : areaGroupList1) {
                            three.setLevel(3);
                        }
                        eduCameraAreaGroup.setChildren(areaGroupList1);
                    }
                }
                areaGroup.setChildren(areaGroupList);
            }
        }

        return parentList;

    }

    @Override
    public List<H5ThemeListVO> listParentTheme(Long parentId) {
        // 判断是否有学生信息
        List<EduStudent> studentList = studentService.listStudentByParent(parentId).getData();
        if (CollUtil.isEmpty(studentList)) {
            return new ArrayList<>();
        }
        // 判断是否有班级信息
        List<Long> classIds = studentList.stream().map(EduStudent::getClassId).collect(Collectors.toList());
        if (CollUtil.isEmpty(classIds)) {
            return new ArrayList<>();
        }
        // 家长查询符合条件的主题列表数据
        List<EduCameraStrategyTheme> themeList = themeMapper.selectThemeList(classIds, LocalDate.now().getDayOfWeek().getValue());
        if (CollUtil.isEmpty(themeList)) {
            return new ArrayList<>();
        }
        // 返回数据
        List<H5ThemeListVO> returnList = new ArrayList<>();
        for (EduCameraStrategyTheme theme : themeList) {
            H5ThemeListVO h5ThemeListVO = new H5ThemeListVO();
            BeanUtils.copyProperties(theme, h5ThemeListVO);
            // 查询家长在当前主题是否有关联摄像头数据
            List<EduCamera> cameraList = new ArrayList<>();
            // 固定主题
            if (ThemeTypeEnum.FIXED_TYPE.getType().equals(theme.getThemeType())) {
                cameraList = cameraMapper.selectList(new LambdaQueryWrapper<>(new EduCamera())
                    .eq(EduCamera::getCommonType, CommonTypeEnum.PRIVATE_TYPE.getType())
                    .in(EduCamera::getDeptId, classIds));
            } else if (ThemeTypeEnum.UN_FIXED_TYPE.getType().equals(theme.getThemeType())) {
                // 不固定主题
                cameraList = cameraMapper.selectList(new LambdaQueryWrapper<>(new EduCamera())
                    .eq(EduCamera::getCommonType, CommonTypeEnum.PUBLIC_TYPE.getType())
                    .in(EduCamera::getId, openCameraService.list(new LambdaQueryWrapper<>(new EduCameraStrategyOpenCamera())
                        .eq(EduCameraStrategyOpenCamera::getOpenId, theme.getId()))
                        .stream().map(EduCameraStrategyOpenCamera::getCameraId).collect(Collectors.toList())));
            }
            if (CollUtil.isEmpty(cameraList)) {
                continue;
            }
            h5ThemeListVO.setCameraList(cameraList.stream().map(eduCamera -> {
                ListCameraVO listCameraVO = new ListCameraVO();
                BeanUtils.copyProperties(eduCamera, listCameraVO);
                return listCameraVO;
            }).collect(Collectors.toList()));
            returnList.add(h5ThemeListVO);
        }
        return returnList;
    }
}
