package com.template.services.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.template.config.ScheduleConfig;
import com.template.model.dto.WarningUserDto;
import com.template.model.pojo.*;
import com.template.mapper.SmartRelationMapper;
import com.template.model.result.PageUtils;
import com.template.model.vo.SmartRelationAppVo;
import com.template.model.vo.SmartRelationVo;
import com.template.model.vo.UserVo;
import com.template.services.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author ceshi
 * @since 2024-06-28
 */
@Service
public class SmartRelationServiceImpl extends ServiceImpl<SmartRelationMapper, SmartRelation> implements SmartRelationService {

    @Resource
    private ScheduleConfig scheduleConfig;

    @Autowired
    SmartAccessService smartAccessService;

    @Autowired
    SmartFaceDiscernService smartFaceDiscernService;

    @Autowired
    SmartUserService smartUserService;

    @Autowired
    SmartAttendanceService smartAttendanceService;


    @Autowired
    SmartRelationMapper smartRelationMapper;


    @Async
    @Scheduled(cron = "0 20 0 * * ? ")//每天凌晨一点
//    @Scheduled(cron = "0 6 15 * * ? ")//每天凌晨一点
    public void getAccessSmartRelation() {
        if (scheduleConfig.getIsOpen().equals("1")) {
            DateTimeFormatter pattern = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            LocalDateTime now = LocalDateTime.now();
            LocalDateTime start = now.withHour(0).withMinute(0).withSecond(0).minusDays(1);
            LocalDateTime end = now.withHour(23).withMinute(59).withSecond(59).minusDays(1);
            String format = start.format(pattern);
//            找到昨天的所有数据
            List<SmartAccess> accessList = smartAccessService.toDatelist(start, end);

            for (SmartAccess smartAccess : accessList) {
                String dateTime = smartAccess.getDateTime();
                LocalDateTime date = LocalDateTime.parse(dateTime, pattern);
                LocalDateTime startTime = date.minusSeconds(5);
                LocalDateTime endTime = date.plusSeconds(5);
                Integer userId = smartAccess.getUserId();
                SmartUser smartUser = smartUserService.getSmartById(userId);
                String type = smartAccess.getType();
                List<SmartAccess> accesses = smartAccessService.toDateAndPlacelist(startTime, endTime, type);
                if (ObjectUtils.isNotEmpty(accesses) && accesses.size() > 0) {

                    for (SmartAccess access : accesses) {
                        Integer userId1 = access.getUserId();
                        if (!userId.equals(userId1) && userId != 0 && userId1 != 0) {
                            SmartUser smartById = smartUserService.getSmartById(userId1);
//                        判断是否已添加，有的话则加1
                            LambdaQueryWrapper<SmartRelation> wrapper = new LambdaQueryWrapper<>();
                            wrapper.eq(SmartRelation::getUserId, userId)
                                    .eq(SmartRelation::getRelationId, userId1)
                                    .eq(SmartRelation::getDateTime, format);
                            SmartRelation one = this.getOne(wrapper);
                            if (ObjectUtils.isEmpty(one)) {
                                SmartRelation smartRelation = new SmartRelation();
                                smartRelation.setUserId(userId);
                                smartRelation.setRelationId(userId1);
                                if (ObjectUtils.isNotEmpty(smartUser)) {
                                    smartRelation.setName(smartUser.getName());
                                }
                                if (ObjectUtils.isNotEmpty(smartById)) {
                                    smartRelation.setRelationName(smartById.getName());
                                }
                                smartRelation.setCount(1);
                                smartRelation.setDateTime(format);
                                this.save(smartRelation);
                            } else {
                                Integer count = one.getCount();
                                count = count + 1;
                                one.setCount(count);
                                this.updateById(one);
                            }

                        }
                    }

                }

            }

        }
    }

    @Async
    @Scheduled(cron = "0 30 2 * * ? ")//每天凌晨两点
//    @Scheduled(cron = "0 25` * * * ? ")//每天凌晨两点
    public void getFaceDiscernListSmartRelation() {
        if (scheduleConfig.getIsOpen().equals("1")) {
            DateTimeFormatter pattern = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            LocalDateTime now = LocalDateTime.now();
            LocalDateTime start = now.withHour(0).withMinute(0).withSecond(0).minusDays(1);
            LocalDateTime end = now.withHour(23).withMinute(59).withSecond(59).minusDays(1);

            String format = start.format(pattern);

//            找到昨天的所有数据
            List<SmartFaceDiscern> faceDiscernList = smartFaceDiscernService.toDateList(start, end);

            for (SmartFaceDiscern faceDiscern : faceDiscernList) {
                String dateTime = faceDiscern.getDateTime();
                LocalDateTime date = LocalDateTime.parse(dateTime, pattern);
                LocalDateTime startTime = date.minusSeconds(5);
                LocalDateTime endTime = date.plusSeconds(5);
                Integer userId = faceDiscern.getUserId();
                SmartUser smartUser = smartUserService.getSmartById(userId);
                String location = faceDiscern.getLocation();
                List<SmartFaceDiscern> faceDiscerns = smartFaceDiscernService.toDateAndPlacelist(startTime, endTime, location);
                if (ObjectUtils.isNotEmpty(faceDiscerns) && faceDiscerns.size() > 0) {

                    for (SmartFaceDiscern faceDiscern1 : faceDiscerns) {
                        Integer userId1 = faceDiscern1.getUserId();
                        if (!userId.equals(userId1) && userId != 0 && userId1 != 0) {
                            SmartUser smartById = smartUserService.getSmartById(userId1);
//                        判断是否已添加，有的话则加1
                            LambdaQueryWrapper<SmartRelation> wrapper = new LambdaQueryWrapper<>();
                            wrapper.eq(SmartRelation::getUserId, userId)
                                    .eq(SmartRelation::getRelationId, userId1)
                                    .eq(SmartRelation::getDateTime, format);
                            SmartRelation one = this.getOne(wrapper);
                            if (ObjectUtils.isEmpty(one)) {
                                SmartRelation smartRelation = new SmartRelation();
                                smartRelation.setUserId(userId);
                                smartRelation.setRelationId(userId1);
                                if (ObjectUtils.isNotEmpty(smartUser)) {
                                    smartRelation.setName(smartUser.getName());
                                }
                                if (ObjectUtils.isNotEmpty(smartById)) {
                                    smartRelation.setRelationName(smartById.getName());
                                }
                                smartRelation.setDateTime(format);
                                smartRelation.setCount(1);
                                this.save(smartRelation);
                            } else {
                                Integer count = one.getCount();
                                count = count + 1;
                                one.setCount(count);
                                this.updateById(one);
                            }

                        }
                    }
                }

            }

        }
    }

    @Async
    @Scheduled(cron = "0 30 3 * * ? ")//每天凌晨一点
//    @Scheduled(cron = "0 38 15 * * ? ")//每天凌晨一点
    public void getAttendanceListSmartRelation() {
        if (scheduleConfig.getIsOpen().equals("1")) {
            DateTimeFormatter pattern = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            LocalDateTime now = LocalDateTime.now();
//            LocalDateTime now = LocalDateTime.now().withMonth(6).withDayOfMonth(26);
            LocalDateTime start = now.withHour(0).withMinute(0).withSecond(0).minusDays(1);
            LocalDateTime end = now.withHour(23).withMinute(59).withSecond(59).minusDays(1);
            String format = start.format(pattern);

//            找到昨天的所有数据
            List<SmartAttendance> attendanceList = smartAttendanceService.toDateList(start, end);

            for (SmartAttendance smartAttendance : attendanceList) {
                Date attendTime = smartAttendance.getAttendTime();
                LocalDateTime date = LocalDateTime.ofInstant(attendTime.toInstant(), ZoneId.systemDefault());
                LocalDateTime startTime = date.minusSeconds(5);
                LocalDateTime endTime = date.plusSeconds(5);
//              获取班级
                Integer classId = smartAttendance.getClassId();
                Integer userId = smartAttendance.getUserId();
//                获取名字
                String userName = smartAttendance.getXwUserName();

                List<SmartAttendance> attendances = smartAttendanceService.toDateAndPlacelist(startTime, endTime, classId);
                if (ObjectUtils.isNotEmpty(attendances) && attendances.size() > 0) {
                    for (SmartAttendance attendance : attendances) {
                        Integer userId1 = attendance.getUserId();
                        String userName1 = attendance.getXwUserName();
                        if (!userId.equals(userId1)) {
                            //                        判断是否已添加，有的话则加1
                            LambdaQueryWrapper<SmartRelation> wrapper = new LambdaQueryWrapper<>();
                            wrapper.eq(SmartRelation::getUserId, userId)
                                    .eq(SmartRelation::getRelationId, userId1)
                                    .eq(SmartRelation::getDateTime, format);
                            SmartRelation one = this.getOne(wrapper);
                            if (ObjectUtils.isEmpty(one)) {
                                SmartRelation smartRelation = new SmartRelation();
                                smartRelation.setUserId(userId);
                                smartRelation.setRelationId(userId1);
                                smartRelation.setName(userName);
                                smartRelation.setRelationName(userName1);

                                smartRelation.setDateTime(format);
                                smartRelation.setCount(1);
                                this.save(smartRelation);
                            } else {
                                Integer count = one.getCount();
                                count = count + 1;
                                one.setCount(count);
                                this.updateById(one);
                            }
                        }

                    }
                }


            }

        }
    }



    @Override
    public PageUtils<SmartRelationVo> getList(int currentPage, int pageCount, Integer userId, String startTime, String endTime) {
        Page<SmartRelationVo> page = new Page<>();
        page.setCurrent(currentPage);
        page.setSize(pageCount);
        IPage<SmartRelationVo> result = smartRelationMapper.getList(page, userId, startTime, endTime);

        return new PageUtils(result);
    }

    @Override
    public PageUtils<SmartRelationAppVo> getAppList(int currentPage, int pageCount, Integer userId, String startTime, String endTime) {
        Page<SmartRelationAppVo> page = new Page<>();
        page.setCurrent(currentPage);
        page.setSize(pageCount);
        IPage<SmartRelationAppVo> result = smartRelationMapper.getAppList(page, userId, startTime, endTime);

        return new PageUtils(result);
    }
}
