package cc.smtweb.system.bpm.spring.dataCacheInit;

import cc.smtweb.framework.core.cache.redis.RedisManager;
import cc.smtweb.framework.core.db.DbEngine;
import cc.smtweb.system.bpm.web.sys.base.attachFolder.AttachFolder;
import cc.smtweb.system.bpm.web.sys.base.attachFolder.pojo.AttachFolderPojo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;


/**
 * 实体【[附件目录表](TB_SYS_ATTACH_FOLDER)】的缓存Buffer类
 */
@Component
public final class AttachFolderEntityBuffer {
    @Autowired
    private RedisManager redisManager;
    @Autowired
    private DbEngine dbEngine;

    public static final String cacheKey = "attach_folder_";


    //根据附件路径和期间获取对象
    public AttachFolderPojo getByPath(String attachPath, String period) {

        return redisManager.get(cacheKey + attachPath + "_" + period, AttachFolderPojo.class);

    }

    //根据附件路径和期间获取当前最大序号
    public int getMaxSeq(String attachPath, String period) {
        AttachFolderPojo bean = getByPath(attachPath, period);
        if (bean == null) return 0;
        return bean.getFolderMaxSeq();
    }

    //根据附件路径和期间获取当前文件数
    public int getFileCount(String attachPath, String period) {
        AttachFolderPojo bean = getByPath(attachPath, period);
        if (bean == null) return 0;
        return bean.getFolderFileCount().intValue();
    }

    //初始化数据
    public void initData() {
        //查询所有数据
        String sql = "select folder_id,folder_path,folder_period,folder_max_seq,folder_file_count from " + AttachFolder.ENTITY_NAME;
        List<AttachFolder> returnList = dbEngine.query(sql, AttachFolder.class);
        if (null != returnList && returnList.size() > 0) {
            for (AttachFolder pojo : returnList) {
                AttachFolderPojo p = new AttachFolderPojo();
                p.setFolderId(pojo.getId());
                p.setFolderAttachPath(pojo.getPath());
                p.setFolderFileCount(pojo.getFileCount());
                p.setFolderPeriod(pojo.getPeriod());
                p.setFolderMaxSeq(pojo.getMaxSeq());
                redisManager.set(cacheKey + pojo.getPath() + "_" + pojo.getPeriod(), p, 0);
            }
        }
    }

    //写入一个数据
    public void putOneData(AttachFolderPojo pojo) {
        //查询所有数据
        redisManager.set(cacheKey + pojo.getFolderAttachPath() + "_" + pojo.getFolderPeriod(), pojo, 0);
    }

}
