package com.jpsoft.shinestar.scheduled;

import com.jpsoft.shinestar.config.OSSConfig;
import com.jpsoft.shinestar.modules.base.entity.PersonDeviceLog;
import com.jpsoft.shinestar.modules.base.service.PersonDeviceFilterLogService;
import com.jpsoft.shinestar.modules.base.service.PersonDeviceLogService;
import com.jpsoft.shinestar.modules.common.utils.OSSUtil;
import com.jpsoft.shinestar.modules.sys.entity.SysLog;
import com.jpsoft.shinestar.modules.sys.service.SysLogService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Profile;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.util.Date;
import java.util.List;

@Component
@Slf4j
@Profile(value = {"deprecated"})
public class CleanVisitorRecordTask {

    @Autowired
    private PersonDeviceFilterLogService personDeviceFilterLogService;

    @Autowired
    private PersonDeviceLogService personDeviceLogService;

    @Autowired
    private SysLogService sysLogService;

    @Autowired
    private OSSConfig ossConfig;

    //每1小时执行一次
//    @Scheduled(cron="0 0 0/1 * * ?")
    public void run(){
        log.warn("删除过期访客记录任务开始");

        List<PersonDeviceLog> logList = personDeviceLogService.findExpiredVisitorRecord(100);

        int removeImageCount = 0;
        int removeRawCount = 0;
        int removeFilterCount = 0;

        //删除上传图片
        for (PersonDeviceLog personDeviceLog : logList) {
            String faceImage = personDeviceLog.getFaceImage();

            if(StringUtils.isNotBlank(faceImage)){
                try {
                    if (OSSUtil.deleteFile(ossConfig, faceImage)) {
                        removeImageCount++;
                    }
                }
                catch (Exception ex){
                    log.error(ex.getMessage());
                }
            }

            removeRawCount += personDeviceLogService.delete(personDeviceLog.getId());
        }

        //删除过滤记录->过滤表中都是保存person_id!=0记录
//      removeFilterCount = personDeviceFilterLogService.deleteExpiredVisitorRecord(100);

        //增加系统日志
        SysLog sysLog = new SysLog();
        sysLog.setPointcut("清除过期访问者测温记录");
        sysLog.setRemark(String.format("删除图片数量:%s,删除原始测温记录:%s",
                removeImageCount,removeRawCount,removeFilterCount));
        sysLog.setCreateTime(new Date());

        sysLogService.insert(sysLog);

        log.warn("删除过期访客记录任务结束");
    }

    public static void main(String[] args) {
        String str  = " ";

        System.out.println(StringUtils.isNotEmpty(str));
        System.out.println(StringUtils.isNotBlank(str));
    }
}
