package com.mortals.xhx.daemon.task;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.date.DateUtil;
import com.mortals.framework.common.Rest;
import com.mortals.framework.exception.AppException;
import com.mortals.framework.service.ITask;
import com.mortals.framework.service.ITaskExcuteService;
import com.mortals.framework.utils.ServletUtils;
import com.mortals.xhx.base.system.upload.service.UploadService;
import com.mortals.xhx.common.code.YesNoEnum;
import com.mortals.xhx.module.hik.face.model.req.img.ImgReq;
import com.mortals.xhx.module.hik.face.service.IHikFaceService;
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 org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.Date;
import java.util.List;

import static java.util.stream.Collectors.toList;

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

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


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

        statPeople();

        donwnloadSnap();

    }

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


    private void donwnloadSnap() {
        //下载最近一天的抓拍数据
        RealtimeDataflowQuery realtimeDataflowQuery = new RealtimeDataflowQuery();
        realtimeDataflowQuery.setDetectTimeStart(DateUtil.yesterday().toStringDefaultTimeZone());
        //realtimeDataflowQuery.setPicture("");

        List<RealtimeDataflowEntity> updateList = realtimeDataflowService.find(realtimeDataflowQuery).stream().filter(f -> ObjectUtils.isEmpty(f.getPicture()) && !ObjectUtils.isEmpty(f.getPicUri())).map(item -> {
            ImgReq imgReq = new ImgReq();
            imgReq.setUrl(item.getPicUri());
            Rest<String> rest = faceService.downloadPicture(imgReq);
            if (YesNoEnum.YES.getValue() == rest.getCode()) {
                byte[] bytes = Base64.decode(rest.getData());
                if (bytes.length > 0) {
                    InputStream inputStream = new ByteArrayInputStream(bytes);
                    MultipartFile file = ServletUtils.getMultipartFile(inputStream, "snap.jpg");
                    String filePath = uploadService.saveFileUpload(file, "file/fileupload", null);
                    item.setPicture(filePath);
                    item.setUpdateTime(new Date());
                    item.setUpdateUserId(1L);
                    item.setUpdateUserName("system");
                    return item;
                }
            }
            return null;
        }).filter(f -> f != null).collect(toList());
        if (ObjectUtils.isEmpty(updateList)) {
            realtimeDataflowService.update(updateList, null);
        }
    }


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