package com.mortals.xhx.daemon.task;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.RandomUtil;
import com.mortals.framework.exception.AppException;
import com.mortals.framework.model.PageInfo;
import com.mortals.framework.service.ITask;
import com.mortals.framework.service.ITaskExcuteService;
import com.mortals.framework.util.DataUtil;
import com.mortals.framework.util.DateUtils;
import com.mortals.xhx.base.system.upload.service.UploadService;
import com.mortals.xhx.common.code.CheckInMethodEnum;
import com.mortals.xhx.module.monitor.model.MonitorAlarmEntity;
import com.mortals.xhx.module.monitor.model.MonitorAlarmQuery;
import com.mortals.xhx.module.monitor.model.MonitorAlarmRecordEntity;
import com.mortals.xhx.module.monitor.service.MonitorAlarmRecordService;
import com.mortals.xhx.module.monitor.service.MonitorAlarmService;
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.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

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

    @Autowired
    private RealtimeDataflowService realtimeDataflowService;
    @Autowired
    private RealtimeDataflowStatService realtimeDataflowStatService;
    @Autowired
    private UploadService uploadService;
    @Autowired
    private MonitorAlarmService monitorAlarmService;
    @Autowired
    private MonitorAlarmRecordService monitorAlarmRecordService;


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

        //随机添加人员监控
       // randomAlarmPeople();

    }


    private void randomAlarmPeople() {

        RealtimeDataflowQuery realtimeDataflowQuery = new RealtimeDataflowQuery();
        realtimeDataflowQuery.setDetectTimeStart(DateUtil.offsetDay(new Date(),-7).toDateStr());
        realtimeDataflowQuery.setDetectTimeEnd(DateUtil.today());

        PageInfo pageInfo = new PageInfo();
        pageInfo.setPrePageResult(200);


        realtimeDataflowService.find(realtimeDataflowQuery,pageInfo,null).getList().stream().filter(f->RandomUtil.randomInt(1,100)>50).forEach(item->{
            //新增
            MonitorAlarmEntity monitorAlarm = new MonitorAlarmEntity();
            monitorAlarm.initAttrValue();
            monitorAlarm.setSiteId(item.getSiteId());
            monitorAlarm.setSiteName(item.getSiteName());
            monitorAlarm.setIdentifyNum(RandomUtil.randomInt(10));

            monitorAlarm.setIdNumber("5101061994072"+RandomUtil.randomInt(10000,99999));
            monitorAlarm.setLastIdentifyTime(item.getDetectTime());
            monitorAlarm.setYear(DataUtil.converStr2Int(DateUtils.getThisYear(), 2023));
            monitorAlarm.setMonth(DataUtil.converStr2Int(DateUtils.getCurrMonth(), 1));
            monitorAlarm.setDay(DateUtils.getCurrentMonthDay());
            monitorAlarm.setCreateTime(new Date());
            monitorAlarm.setCreateUserName("system");
            monitorAlarm.setCreateUserId(1L);
            monitorAlarmService.save(monitorAlarm);

            //新增当前用户信息告警详细记录
            MonitorAlarmRecordEntity monitorAlarmRecordEntity = new MonitorAlarmRecordEntity();
            monitorAlarmRecordEntity.setAlarmId(monitorAlarm.getId());


            ArrayList<String> list = new ArrayList<>();

            list.add("工程规划许可、用地规划许可、规划核实");
            list.add("不动产一件事一次办业务（二手房买卖、抵押、换证、离婚析产、变更）");
            list.add("不动产档案查询业务（仅限不动产权证产调、查封、抵押情况等）");
            list.add("住房信息查询（接新房交契税、房屋套数查询等）");
            list.add("普通公路涉路施工许可、超限运输许可、市航务业务");
            list.add("企业职工社会保险费补缴申报（距申报当月6个月以上的补缴）");

            monitorAlarmRecordEntity.setReservationService(list.get(RandomUtil.randomInt(0,5)));
            monitorAlarmRecordEntity.setReservationNumber("V4BCB");
            monitorAlarmRecordEntity.setMonitorTime(item.getDetectTime());
            monitorAlarmRecordEntity.setMonitorDevice(item.getDevice());
            monitorAlarmRecordEntity.setCheckInMethod(CheckInMethodEnum.自动签到.getValue());
            monitorAlarmRecordEntity.setMonitorCertificate(item.getPicture());
            monitorAlarmRecordEntity.setCreateTime(new Date());
            monitorAlarmRecordEntity.setCreateUserName("system");
            monitorAlarmRecordEntity.setCreateUserId(1L);
            monitorAlarmRecordService.save(monitorAlarmRecordEntity);
        });




    }

    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);
    }
}
