
package com.tmerclub.cloud.common.leaf.segment.dao.impl;

import com.tmerclub.cloud.common.leaf.segment.dao.IDAllocDao;
import com.tmerclub.cloud.common.leaf.segment.mapper.IDAllocMapper;
import com.tmerclub.cloud.common.leaf.segment.model.LeafAlloc;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author leaf
 */
@Component
public class IDAllocDaoImpl implements IDAllocDao {

    @Autowired
    private IDAllocMapper idAllocMapper;

    @Override
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRES_NEW)
    @GlobalTransactional(propagation = io.seata.tm.api.transaction.Propagation.NOT_SUPPORTED)
    public List<LeafAlloc> getAllLeafAllocs() {
        return idAllocMapper.getAllLeafAllocs();
    }

    @Override
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRES_NEW)
    @GlobalTransactional(propagation = io.seata.tm.api.transaction.Propagation.NOT_SUPPORTED)
    public LeafAlloc updateMaxIdAndGetLeafAlloc(String tag, int length) {
        idAllocMapper.updateMaxId(tag);
        LeafAlloc result = idAllocMapper.getLeafAlloc(tag);
        // 长度过长，要重新初始化成step
        if (String.valueOf(result.getMaxId()).length() > length) {
            idAllocMapper.updateMaxIdToStep(tag);
            result.setMaxId(result.getStep());
        }
        return result;
    }

    @Override
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRES_NEW)
    @GlobalTransactional(propagation = io.seata.tm.api.transaction.Propagation.NOT_SUPPORTED)
    public LeafAlloc updateMaxIdByCustomStepAndGetLeafAlloc(LeafAlloc leafAlloc, int length) {
        idAllocMapper.updateMaxIdByCustomStep(leafAlloc);
        LeafAlloc result = idAllocMapper.getLeafAlloc(leafAlloc.getKey());
        // 长度过长，要重新初始化成step
        if (String.valueOf(result.getMaxId()).length() > length) {
            // 如果超过最大值，就按最大值的id来返回即可
            long maxValue = Math.round(Math.pow(10, length)) - 1;
            result.setValue(result.getMaxId() - leafAlloc.getStep());
            result.setMaxId(maxValue);
            // 初始化id的获取数量
            leafAlloc.setStep(result.getStep());
            // 初始化表中的id数据
            idAllocMapper.updateMaxIdToStep(leafAlloc.getKey());
        }
        return result;
    }

    @Override
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRES_NEW)
    @GlobalTransactional(propagation = io.seata.tm.api.transaction.Propagation.NOT_SUPPORTED)
    public List<String> getAllTags() {
        return idAllocMapper.getAllTags();
    }

}
