package org.springblade.datasource.transform.postgresql;

import cn.hutool.core.collection.CollectionUtil;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springblade.core.tool.exception.ServiceException;
import org.springblade.datasource.support.DynamicDataSourceSupport;
import org.springblade.datasource.transform.ColumnEnum;
import org.springblade.datasource.transform.ColumnInfo;
import org.springblade.datasource.transform.IndexInfo;
import org.springblade.datasource.transform.TableInfo;
import org.springblade.datasource.transform.util.ListUtils;
import org.springblade.etl.entity.bi.ReportDatasource;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author 喜欢番茄火锅
 * @date 2023/8/21 16:42
 */
@Slf4j
public class PostgreSQLCreateTableHandle {


    /**
     * 根据通用表信息创建表对象
     *
     * @param tableInfo
     * @return
     * @author 王瑞
     * @date 2023/8/16
     */
    @SneakyThrows
    public void creatTable(TableInfo tableInfo, ReportDatasource datasource) {

        String columSql = buildColumnSql(tableInfo);
        log.info("创建表sql 语句,sql:{}", columSql);
        String tableCommentSql = buildTableCommentSql(tableInfo.getTableName(), tableInfo.getTableComment());
        log.info("创建表注释sql 语句,sql:{}", tableCommentSql);
        List<String> columnCommentSql = buildColumnCommentSql(tableInfo.getTableName(), tableInfo.getColumnInfo());
        log.info("创建字段注释sql 语句,sql:{}", columnCommentSql);
        Connection connection = DynamicDataSourceSupport.createConnection(datasource);
        Statement statement = connection.createStatement();
        ResultSet tables = connection.getMetaData().getTables(null, datasource.getDbSchema(), tableInfo.getTableName(), new String[]{"TABLE", "VIEW"});
        if (tables.next()) {
            List<ColumnInfo> sourceColumn = new PostgreSQLParseTableHandle().getSourceColumn(tableInfo.getTableName(), connection.getMetaData(), datasource.getDbSchema());
            List<String> collect = tableInfo.getColumnInfo().stream().map(ColumnInfo::getColumnName).collect(Collectors.toList());
            List<String> collect2 = sourceColumn.stream().map(ColumnInfo::getColumnName).collect(Collectors.toList());
            if (!ListUtils.equalLists(collect, collect2)) {
                throw new ServiceException("PostgreSQL 源,表名称:" + tableInfo.getTableName() + "已存在且字段不符!");
            }
            return;
        }

        statement.executeUpdate(columSql);
        statement.executeUpdate(tableCommentSql);
        for (String s : columnCommentSql) {
            statement.executeUpdate(s);
        }
        statement.close();
    }


    private String buildColumnSql(TableInfo tableInfo) {
        StringBuilder fieldSql = new StringBuilder();
        tableInfo.getColumnInfo().stream().forEach(columnInfo -> fieldSql.append(String.format(
                "%s %s ,",
                columnInfo.getColumnName(),
                getColumnType(columnInfo)
        )));

        StringBuilder primaryKey = new StringBuilder();
        List<IndexInfo> collect = null;
        if (CollectionUtil.isNotEmpty(tableInfo.getIndexInfo())) {
            collect = tableInfo.getIndexInfo().stream().filter(IndexInfo::getPrimaryKey).collect(Collectors.toList());
            if (CollectionUtil.isNotEmpty(collect)) {
                collect.get(0).getIndexColumn().stream().forEach(v -> {
                    primaryKey.append(v.getColumnName() + ",");
                });
                if (StringUtils.isNotBlank(primaryKey)) {
                    primaryKey.deleteCharAt(primaryKey.length() - 1);
                    fieldSql.append(String.format("PRIMARY KEY (%s)", primaryKey));
                }
            }
        } else {
            fieldSql.deleteCharAt(fieldSql.length() - 1);
        }
        return String.format("CREATE TABLE %s (%s) ;", tableInfo.getTableName(), fieldSql);
    }


    public String getColumnType(ColumnInfo columnInfo) {
        ColumnEnum columnEnum = columnInfo.getColumnType();
        switch (columnEnum) {
            case DECIMAL:
                return "NUMERIC(30, 4)";
            case STRING:
                Integer columnSize = columnInfo.getColumnSize();
                if (columnSize != null && columnSize > 255) {
                    return "text";
                }
                if (columnSize != null && columnSize < 1) {
                    return "text";
                }
                return "varchar(255)";
            case LONG:
                return "bigint";
            case INTEGER:
                return "int";
            case DOUBLE:
                return "double precision";
            case FLOAT:
                return "float";
            case DATE:
                return "date";
            case BOOL:
                return "bit(1)";
            default:
                return "";
        }

    }

    private String buildTableCommentSql(String tableName, String tableComment) {
        return String.format("COMMENT ON TABLE %s is '%s' ", tableName, tableComment);
    }

    private List<String> buildColumnCommentSql(String tableName, List<ColumnInfo> columnComment) {
        return columnComment.stream().map(columnInfo ->
                String.format(
                        "COMMENT ON COLUMN %s.%s is '%s' ",
                        tableName,
                        columnInfo.getColumnName(),
                        columnInfo.getColumnComments()
                )
        ).collect(Collectors.toList());
    }
}
