package com.boman.system.utils;

import com.boman.common.core.utils.SpringUtils;
import com.boman.common.redis.RedisKey;
import com.boman.common.redis.service.RedisService;
import com.boman.gen.domain.GenTableColumn;
import com.boman.system.mapper.StandardlyMapper;
import org.apache.commons.collections.CollectionUtils;

import java.util.List;

/**
 * @author shiqian
 * @description
 * @date 2021年03月23日 16:04
 **/
public class IdUtils {


    public static Long getMaxId(String tableName, String pkName) {
        RedisService redisService = SpringUtils.getBean(RedisService.class);
        String sequencesKey = RedisKey.SEQ + tableName.toUpperCase();
        boolean isExist = redisService.exists(sequencesKey);
        if (isExist) {
            return redisService.increment(sequencesKey);
        }

        // 查数据库
        StandardlyMapper mapper = SpringUtils.getBean(StandardlyMapper.class);
        Long maxId = mapper.selectMaxId(tableName, pkName);
        if (null == maxId || maxId <= 0) {
            maxId = 1L;
            redisService.setCacheObject(sequencesKey, maxId);
        } else {
            redisService.increment(sequencesKey, ++maxId);
        }

        return maxId;
    }

    public static String getPkName(List<GenTableColumn> columnList) {
        if (CollectionUtils.isEmpty(columnList)) {
            throw new IllegalArgumentException("获取主键失败");
        }

        for (GenTableColumn tableColumn : columnList) {
            if ("1".equalsIgnoreCase(tableColumn.getIsPk())) {
                return tableColumn.getColumnName();
            }
        }

        throw new IllegalArgumentException("获取主键失败");
    }

}
