package com.ycwl.basic.task;


import com.ycwl.basic.device.DeviceFactory;
import com.ycwl.basic.device.operator.IDeviceStorageOperator;
import com.ycwl.basic.integration.common.manager.DeviceConfigManager;
import com.ycwl.basic.integration.device.service.DeviceIntegrationService;
import com.ycwl.basic.integration.common.response.PageResponse;
import com.ycwl.basic.integration.device.dto.device.DeviceV2DTO;
import java.util.stream.Collectors;
import com.ycwl.basic.model.pc.device.entity.DeviceConfigEntity;
import com.ycwl.basic.model.pc.device.entity.DeviceEntity;
import com.ycwl.basic.model.pc.device.req.DeviceReqQuery;
import com.ycwl.basic.model.pc.device.resp.DeviceRespVO;
import com.ycwl.basic.repository.DeviceRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Profile;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

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

@Component
@EnableScheduling
@Slf4j
@Profile("prod")
public class VideoPieceCleaner {
    @Autowired
    private DeviceIntegrationService deviceIntegrationService;
    @Autowired
    private DeviceRepository deviceRepository;

    @Scheduled(cron = "0 0 0 * * ?")
    public void clean() {
        log.info("开始删除视频文件");
        // 通过zt-device服务获取所有激活设备
        PageResponse<DeviceV2DTO> deviceListResponse = deviceIntegrationService.listDevices(1, 10000, null, null, null, 1, null, null);
        if (deviceListResponse == null || deviceListResponse.getList() == null) {
            return;
        }
        for (DeviceV2DTO device : deviceListResponse.getList()) {
            DeviceConfigManager config = deviceRepository.getDeviceConfigManager(device.getId());
            DeviceConfigEntity dConfig = deviceRepository.getDeviceConfig(device.getId());
            Integer storeExpireDay = config.getInteger("store_expire_day");
            if (storeExpireDay == null || storeExpireDay <= 0) {
                continue;
            }
            IDeviceStorageOperator storageOperator = DeviceFactory.getDeviceStorageOperator(device, dConfig);
            if (storageOperator == null) {
                continue;
            }
            storageOperator.removeFilesBeforeDate(new Date(System.currentTimeMillis() - storeExpireDay * 24 * 60 * 60 * 1000));
            log.info("删除视频文件完成");
        }
    }

}
