package com.mortals.xhx.daemon.task;

import cn.hutool.core.date.DateUtil;
import com.mortals.framework.exception.AppException;
import com.mortals.framework.service.ITask;
import com.mortals.framework.service.ITaskExcuteService;
import com.mortals.xhx.base.system.upload.service.UploadService;
import com.mortals.xhx.module.realtime.model.RealtimeDataflowEntity;
import com.mortals.xhx.module.realtime.model.RealtimeDataflowQuery;
import com.mortals.xhx.module.realtime.model.RealtimeDataflowStatEntity;
import com.mortals.xhx.module.realtime.model.RealtimeDataflowStatQuery;
import com.mortals.xhx.module.realtime.service.RealtimeDataflowService;
import com.mortals.xhx.module.realtime.service.RealtimeDataflowStatService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.Date;
import java.util.List;

/**
 * 人流统计接口
 */
@Slf4j
@Service("RealTimePeopleStatTask")
public class RealTimePeopleStatTaskImpl implements ITaskExcuteService {

    @Autowired
    private RealtimeDataflowService realtimeDataflowService;
    @Autowired
    private RealtimeDataflowStatService realtimeDataflowStatService;
    @Autowired
    private UploadService uploadService;


    @Override
    public void excuteTask(ITask task) throws AppException {
        statPeople();
        delFiles();
    }

    private void delFiles() {
        //保留七天人脸数据
        String endTimeStr = DateUtil.offsetDay(new Date(), -7).toDateStr();
        RealtimeDataflowQuery realtimeDataflowQuery = new RealtimeDataflowQuery();
        realtimeDataflowQuery.setCreateTimeEnd(endTimeStr);
        List<RealtimeDataflowEntity> realtimeDataflowEntities = realtimeDataflowService.find(realtimeDataflowQuery, null);
        log.info("定时删除人流数据,endTimeStr:{},size:{}", endTimeStr, realtimeDataflowEntities.size());
        if (!ObjectUtils.isEmpty(realtimeDataflowEntities)) {
            log.info("需要删除的实时监控数据量:{}", realtimeDataflowEntities.size());
            Long[] delIds = realtimeDataflowEntities.stream().map(i -> i.getId()).toArray(Long[]::new);
            realtimeDataflowService.remove(delIds, null);
            for (RealtimeDataflowEntity entity : realtimeDataflowEntities) {
                if (ObjectUtils.isEmpty(entity.getPicture())) continue;
                uploadService.deleteFile(entity.getPicture());
            }

        }

    }

    private void statPeople() {
        Date startTime = DateUtil.beginOfHour(new Date());
        Date endTime = DateUtil.endOfHour(new Date());
        // 格式化时间为指定格式
        String startTimeStr = DateUtil.format(startTime, "yyyy-MM-dd HH:00:00");
        String endTimeStr = DateUtil.format(endTime, "yyyy-MM-dd HH:59:59");

        RealtimeDataflowQuery realtimeDataflowQuery = new RealtimeDataflowQuery();
        realtimeDataflowQuery.setCreateTimeStart(startTimeStr);
        realtimeDataflowQuery.setCreateTimeEnd(endTimeStr);
        List<RealtimeDataflowEntity> realtimeDataflowEntities = realtimeDataflowService.find(realtimeDataflowQuery, null);
        if (!ObjectUtils.isEmpty(realtimeDataflowEntities)) {
            Long strangerCount = realtimeDataflowEntities.parallelStream().filter(f -> ObjectUtils.isEmpty(f.getIdNumber())).count();
            int total = realtimeDataflowEntities.size();
            Long recognizeCount = total - strangerCount;
            Date date = new Date();
            int year = DateUtil.year(date);
            int month = DateUtil.month(date) + 1;
            int day = DateUtil.dayOfMonth(date);
            int hour = DateUtil.hour(date, true);

            RealtimeDataflowStatQuery realtimeDataflowStatQuery = new RealtimeDataflowStatQuery();
            realtimeDataflowStatQuery.setYear(year);
            realtimeDataflowStatQuery.setMonth(month);
            realtimeDataflowStatQuery.setDay(day);
            realtimeDataflowStatQuery.setHour(hour);
            RealtimeDataflowStatEntity realtimeDataflowStatEntity = realtimeDataflowStatService.selectOne(realtimeDataflowStatQuery);
            if (ObjectUtils.isEmpty(realtimeDataflowStatEntity)) {
                RealtimeDataflowStatEntity statEntity = new RealtimeDataflowStatEntity();
                statEntity.initAttrValue();
                statEntity.setPersonSum(total);
                statEntity.setStrangerSum(strangerCount.intValue());
                statEntity.setRecoginzeSum(recognizeCount.intValue());
                statEntity.setYear(year);
                statEntity.setMonth(month);
                statEntity.setDay(day);
                statEntity.setHour(hour);
                statEntity.setPersonSum(total);
                statEntity.setCreateUserId(1L);
                statEntity.setCreateTime(new Date());
                realtimeDataflowStatService.save(statEntity);
            } else {
                realtimeDataflowStatEntity.setPersonSum(total);
                realtimeDataflowStatEntity.setStrangerSum(strangerCount.intValue());
                realtimeDataflowStatEntity.setRecoginzeSum(recognizeCount.intValue());
                realtimeDataflowStatEntity.setUpdateUserId(1L);
                realtimeDataflowStatEntity.setUpdateTime(new Date());
                realtimeDataflowStatService.update(realtimeDataflowStatEntity);
            }
        }
    }


    @Override
    public void stopTask(ITask task) throws AppException {

    }

    public static void main(String[] args) {
        // 获取当前时间的小时数
        int hour = DateUtil.hour(new Date(), true);
        // 获取当前时间所在小时的开始时间和结束时间
        Date startTime = DateUtil.beginOfHour(new Date());
        Date endTime = DateUtil.endOfHour(new Date());

        // 格式化时间为指定格式
        String startTimeStr = DateUtil.format(startTime, "yyyy-MM-dd HH:00:00");
        String endTimeStr = DateUtil.format(endTime, "yyyy-MM-dd HH:59:59");

        // 输出结果
        System.out.println("当前时间所在小时的开始时间：" + startTimeStr);
        System.out.println("当前时间所在小时的结束时间：" + endTimeStr);
    }
}
