package com.tykj.dev.device.library.service.impl;

import com.tykj.dev.device.library.repository.DeviceLibraryDao;
import com.tykj.dev.device.library.service.DeviceLibraryCacheService;
import com.tykj.dev.device.library.subject.domin.DeviceLibrary;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Executor;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * DATE:2021-8-11
 * Author:zsp
 */
@Service
@CacheConfig(cacheNames = "devicesLibraryList")
@Slf4j
public class CacheLibraryServiceImpl implements DeviceLibraryCacheService {

    @Autowired
    private DeviceLibraryDao deviceLibraryDao;

    @Autowired
    @Qualifier("taskExecutor")
    private Executor executor;
//    @Autowired
//    private ConcurrentMapCacheManager mapCacheManager;

    @Autowired
    private DeviceLibraryCacheService deviceLibraryCacheService;
    @Override
    @Cacheable(key = "'device'")
    public List<DeviceLibrary> getAllDeviceLibraryList() {
        long start = System.currentTimeMillis();
        List<DeviceLibrary> all = deviceLibraryDao.findAll();
        log.info("创建缓存时间：{}", System.currentTimeMillis() - start);
        return all;
    }

    @Override
    @Cacheable(key = "'deviceByIds'")
    public List<DeviceLibrary> findByIds(List<Integer> ids) {
        List<DeviceLibrary> deviceLibraries = deviceLibraryCacheService.getAllDeviceLibraryList();
        Map<Integer, DeviceLibrary> map = deviceLibraries.stream().collect(Collectors.toMap(DeviceLibrary::getId, Function.identity()));
        List<DeviceLibrary> libraryList = new ArrayList<>();
        ids.forEach(
                id->{
                    if (map.containsKey(id)){
                        DeviceLibrary deviceLibrary = map.get(id);
                        libraryList.add(deviceLibrary);
                    }
                }
        );
        return libraryList;
    }

    @Override
    @CacheEvict(key = "'device'",allEntries=true)
    public void deletAllDeviceLibraryList() {
//        long l = System.currentTimeMillis();
//        List<DeviceLibrary> all = deviceLibraryDao.findAll();
//        System.out.println("更新缓存时间"+(System.currentTimeMillis()-l));
    }

    @Override
    @CacheEvict(key = "'device'",allEntries=true)
    public void asyncUpdateCache() {
        executor.execute(()->{
            deviceLibraryCacheService.getAllDeviceLibraryList();
        });
    }


}
