package com.yida.data.user.service.impl;

import cc.mrbird.febs.common.redis.service.RedisService;
import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
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.attendance.feign.RemoteAttendanceDeviceService;
import com.yida.data.attendance.feign.RemoteAttendanceStrategyService;
import com.yida.data.common.core.entity.attendance.EduAttendanceDevice;
import com.yida.data.common.core.entity.attendance.EduAttendanceDeviceGroup;
import com.yida.data.common.core.entity.user.*;
import com.yida.data.user.dto.DelFaceGroupUserDTO;
import com.yida.data.user.mapper.EduFaceGroupMapper;
import com.yida.data.user.service.*;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 人脸组信息 Service实现
 *
 * @author zhanghaijun
 * @date 2021-06-16 14:09:44
 */
@Slf4j
@Service
@RequiredArgsConstructor
@Transactional
public class EduFaceGroupServiceImpl extends ServiceImpl
        <EduFaceGroupMapper, EduFaceGroup> implements EduFaceGroupService {

    private final EduFaceGroupUserService eduFaceGroupUserService;
    private final EduFaceGroupDeviceService eduFaceGroupDeviceService;
    private final EduFaceGroupStrategyService eduFaceGroupStrategyService;
    private final EduFaceGroupStrategyPlanService eduFaceGroupStrategyPlanService;
    private final EduFaceGroupStrategyPlanTimeService eduFaceGroupStrategyPlanTimeService;

    private final RemoteAttendanceDeviceService remoteAttendanceDeviceService;
    private final RemoteAttendanceStrategyService remoteAttendanceStrategyService;

    private final RedisService redisService;

    @Override
    public IPage<EduFaceGroup> listFaceGroupPage(Page page, String groupName, Long schoolId, Long groupId) {
        IPage<EduFaceGroup> res = baseMapper.listFaceGroupPage(page, groupName, schoolId, groupId);
        // 获取所有设备和设备组id
        List<Long> deviceIds = new ArrayList<>();
        List<Long> groupIds = new ArrayList<>();
        for (EduFaceGroup record : res.getRecords()) {
            if (CollUtil.isNotEmpty(record.getDeviceList())) {
                for (EduFaceGroupDevice groupDevice : record.getDeviceList()) {
                    if (groupDevice.getType() == 0) {
                        deviceIds.add(groupDevice.getDeviceId());
                    } else if (groupDevice.getType() == 1) {
                        groupIds.add(groupDevice.getDeviceId());
                    }
                }
            }
        }
        // 查出所有的设备和设备组
        List<EduAttendanceDevice> devices = remoteAttendanceDeviceService.listDeviceById(deviceIds.toArray(new Long[0]))
                .getData();
        List<EduAttendanceDeviceGroup> groups = remoteAttendanceDeviceService.listDeviceGroupById(groupIds.toArray(new Long[0]))
                .getData();
        // 按id分组方便拿数据
        Map<Long, List<EduAttendanceDevice>> deviceMap = devices.stream()
                .collect(Collectors.groupingBy(EduAttendanceDevice::getId));
        Map<Long, List<EduAttendanceDeviceGroup>> groupMap = groups.stream()
                .collect(Collectors.groupingBy(EduAttendanceDeviceGroup::getId));
        for (EduFaceGroup record : res.getRecords()) {
            if (CollUtil.isNotEmpty(record.getDeviceList())) {
                for (EduFaceGroupDevice groupDevice : record.getDeviceList()) {
                    if (groupDevice.getType() == 0
                            && CollUtil.isNotEmpty(deviceMap)
                            && deviceMap.containsKey(groupDevice.getDeviceId())) {
                        groupDevice.setDeviceName(deviceMap.get(groupDevice.getDeviceId()).get(0).getName());
                        groupDevice.setState(deviceMap.get(groupDevice.getDeviceId()).get(0).getState());
                    } else if (groupDevice.getType() == 1
                            && CollUtil.isNotEmpty(groupMap)
                            && groupMap.containsKey(groupDevice.getDeviceId())) {
                        groupDevice.setDeviceName(groupMap.get(groupDevice.getDeviceId()).get(0).getGroupName());
                    }
                }
            }
        }
        return res;
    }

    @Override
    public void removeFaceGroup(Long groupId) {
        // 删除人脸关联信息 删除下发记录  删除设备上的人脸
        List<EduFaceGroupUser> faceGroupUserList =
                eduFaceGroupUserService
                        .list(Wrappers.lambdaQuery(new EduFaceGroupUser()).eq(EduFaceGroupUser::getFaceGroupId, groupId));
        if (CollUtil.isNotEmpty(faceGroupUserList)) {
            // 删除人脸相关信息
            DelFaceGroupUserDTO dto = new DelFaceGroupUserDTO();
            dto.setFaceGroupId(groupId);
            dto.setFaceIds(faceGroupUserList.stream().map(EduFaceGroupUser::getId).collect(Collectors.toList()));
            eduFaceGroupUserService.delUserBatch(dto);
        }
        // 删除组
        removeById(groupId);
        // TODO 2022/12/21 此处需要删除对应通行策略以及人员绑定关系，附带对应的人员对应策略缓存信息
        // 删除策略
        eduFaceGroupStrategyService.remove(Wrappers.lambdaQuery(new EduFaceGroupStrategy())
                .eq(EduFaceGroupStrategy::getFaceGroupId, groupId));
        // 删除策略附表信息
        eduFaceGroupStrategyPlanService.remove(Wrappers.lambdaQuery(new EduFaceGroupStrategyPlan())
                .eq(EduFaceGroupStrategyPlan::getFaceGroupId, groupId));
        eduFaceGroupStrategyPlanTimeService.remove(Wrappers.lambdaQuery(new EduFaceGroupStrategyPlanTime())
                .eq(EduFaceGroupStrategyPlanTime::getFaceGroupId, groupId));
        // 查询关联的设备信息
        List<EduFaceGroupDevice> list = eduFaceGroupDeviceService.list(
                Wrappers.lambdaQuery(new EduFaceGroupDevice()).eq(EduFaceGroupDevice::getFaceGroupId, groupId));
        if (CollUtil.isEmpty(list)) {
            return;
        }
        EduFaceGroupStrategy eduFaceGroupStrategy = new EduFaceGroupStrategy();
        eduFaceGroupStrategy.setFaceGroupId(groupId);
        eduFaceGroupStrategy.setGroupDeviceList(list);
        remoteAttendanceStrategyService.deleteStrategy(eduFaceGroupStrategy);
//        // 移除对应的缓存
//        if (CollUtil.isNotEmpty(faceGroupUserList)) {
//            for (EduFaceGroupDevice device : list) {
//                for (EduFaceGroupUser groupUser : faceGroupUserList) {
//                    log.info("删除的用户数据===device: {}, user: {}", device, groupUser);
//                    redisService.hdel(CachePrefixConstant.USER_ATTENDANCE_STRATEGY +
//                            groupUser.getUserId().toString() + groupUser.getUserType().toString(), String.valueOf(groupId));
//                }
//            }
//
//        }
    }
}
