package net.northking.cctp.scriptcase.api.component.service;

import net.northking.cctp.common.sequence.SequenceStorage;
import net.northking.cctp.scriptcase.constants.ScriptConstant;
import net.northking.cctp.scriptcase.db.entity.AtuBusinessNo;
import net.northking.cctp.scriptcase.db.service.AtuBusinessNoService;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.integration.redis.util.RedisLockRegistry;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.locks.Lock;

/**
 * 编号存入数据库
 */
@Component
public class SequenceStorageImpl implements SequenceStorage {
    private final static Logger logger = LoggerFactory.getLogger(SequenceStorageImpl.class);
    @Autowired
    private AtuBusinessNoService atuBusinessNoService;
    @Autowired
    private RedisLockRegistry redisLockRegistry;
    @Override
    public void save(String s, long l) {
    }

    @Override
    public Map<String, Long> findAll() {
        Map<String, Long> result = new HashMap<>();
        String redisKey = "atu-script-business-no-UPDATE";
        Lock lock = redisLockRegistry.obtain(redisKey);
        Boolean b = false;
        try {
            b = lock.tryLock();
            if (b) {
                //启动时根据库表数据更新编号
                //业务组件树目录表编号
                atuBusinessNoService.updateComTreeNo();

                List<AtuBusinessNo> list = atuBusinessNoService.findAll();
                String suffix = ScriptConstant.SCRIPT_CASE_NO;
                String after  = ScriptConstant.SCRIPT_CASE;
                for (AtuBusinessNo abn : list) {
                    String projectId = StringUtils.isEmpty(abn.getProjectId())?"tenant":abn.getProjectId();
                    String key = after+":"+abn.getTenantId() + ":"+ suffix + ":" + projectId + ":" + abn.getNoType();
                    result.put(key,abn.getNoValue());
                }
            }
        } catch (Exception e) {
            logger.info(e.getMessage());
        } finally {
            if (b) {
                lock.unlock();
            }
        }
        return result;
    }
}
