package com.boman.web.core.utils;

import com.alibaba.fastjson.JSONArray;
import com.boman.common.core.utils.SpringUtils;
import com.boman.common.redis.RedisKey;
import com.boman.common.redis.service.RedisService;
import com.boman.domain.GenTableColumn;
import com.boman.web.core.mapper.StandardlyMapper;
import org.apache.commons.collections.CollectionUtils;

import java.util.List;

import static com.boman.common.core.utils.obj.ObjectUtils.isEmpty;
import static com.boman.common.core.utils.obj.ObjectUtils.requireNonNull;

/**
 * @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) {
            int result = redisService.increment(sequencesKey);
            return (long) result;
        }

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

        return (long) maxId;
    }

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

        for (GenTableColumn tableColumn : columnList) {
            if (GenTableColumn.IS_PK.equalsIgnoreCase(tableColumn.getIsPk())) {
                return requireNonNull(tableColumn.getColumnName(), "主键名称为空");
            }
        }

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


    public static String getPkName(String tableName) {
        return getPkName(ColumnUtils.getColumnList(tableName));
    }

    public static void putIfNotContains(JSONArray jsonArray, String input) {
        if (isEmpty(jsonArray)) {
            jsonArray = new JSONArray();
        }

        if (!jsonArray.contains(input)) {
            jsonArray.add(input);
        }
    }

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

        for (GenTableColumn tableColumn : columnList) {
            if (GenTableColumn.IS_PK.equalsIgnoreCase(tableColumn.getIsPk())) {
                return tableColumn;
            }
        }

        throw new IllegalArgumentException("不可能到这里的, 一个表连个主键都没有吗？？");
    }
}
