/**
 *
 */
package org.springblade.datasource.transform.dameng;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.IdUtil;
import com.google.common.collect.Lists;
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.*;
import org.springblade.datasource.transform.mysql.SQLColumnTypeEnum;
import org.springblade.datasource.transform.util.ListUtils;
import org.springblade.etl.entity.bi.ReportDatasource;

import java.sql.*;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author wookvn
 */
@Slf4j
public class DamengCreateTableHandle {

    public static String getColumnType(ColumnInfo columnInfo) {
        ColumnEnum columnEnum = columnInfo.getColumnType();
        Integer columnSize = columnInfo.getColumnSize();
        Integer decimalDigits = columnInfo.getDecimalDigits();

        switch (columnEnum) {
            case DECIMAL:
                Integer p = TransformUtil.getColumnSizeOrDecimalDigits(columnSize, 10, 20, 2);
                Integer s = TransformUtil.getColumnSizeOrDecimalDigits(decimalDigits, 0, 10, 0);
                return String.format("DECIMAL(%s,%s)", p, s);
            case STRING:
                if (columnSize != null && columnSize > 4000) {
                    return "TEXT";
                }
                if (columnSize != null && columnSize < 1) {
                    return "TEXT";
                }
                return "VARCHAR(" + columnSize + ")";
            case LONG:
                return "BIGINT";
            case INTEGER:
                return "INT";
            case DOUBLE:
                return "DOUBLE";
            case FLOAT:
                return "FLOAT";
            case DATE:
                return "TIMESTAMP";
            case BOOL:
                return "BIT";
            default:
                return "";
        }
    }

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

        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);
//        List<String> indexSql = buildIndexSql(tableInfo.getTableName(), tableInfo.getIndexInfo());
//        log.info("创建表索引sql 语句,sql:{}", indexSql);
        Connection connection = null;
        connection = DynamicDataSourceSupport.createConnection(datasource);
        Statement statement = connection.createStatement();
        ResultSet tables = connection.getMetaData().getTables(null, datasource.getDsDb(), tableInfo.getTableName(), new String[]{"TABLE", "VIEW"});
        if (tables.next()) {
            List<ColumnInfo> sourceColumn = new DamengCreateTableHandle().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("达梦 源,表名称:" + tableInfo.getTableName() + "已存在且字段不符!");
            }
            return;
        }

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

    }

    private void inspectIndex(TableInfo tableInfo) {
        List<ColumnInfo> columnInfo = tableInfo.getColumnInfo();
        List<IndexInfo> indexInfoList = tableInfo.getIndexInfo();
        if (CollectionUtil.isEmpty(columnInfo) || CollectionUtil.isEmpty(indexInfoList)) {
            return;
        }

        Iterator<IndexInfo> iterator = indexInfoList.iterator();
        while (iterator.hasNext()) {
            IndexInfo indexInfo = iterator.next();

            for (IndexInfo.IndexColumn next : indexInfo.getIndexColumn()) {
                boolean flag = columnInfo.stream().anyMatch(columnName -> {
                    //判断现有的name是否存在集合中
                    return columnName.getColumnName().equalsIgnoreCase(next.getColumnName());
                });
                if (!flag) {
                    iterator.remove();
                    break;
                }
            }

        }
    }

    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("CONSTRAINT i" + IdUtil.fastSimpleUUID() + " PRIMARY KEY (%s)", primaryKey));
                }
            }
        } else {
            fieldSql.deleteCharAt(fieldSql.length() - 1);
        }
        return String.format("CREATE TABLE %s (%s) ;", tableInfo.getTableName(), fieldSql);
    }

    private List<String> buildIndexSql(String tableName, List<IndexInfo> indexInfos) {
        List<String> list = Lists.newArrayList();

        if (CollectionUtil.isEmpty(indexInfos)) {
            return list;
        }
        indexInfos.stream().forEach(indexInfo -> {
                    StringBuilder indexSql = new StringBuilder();
                    indexSql.append(String.format(
                            "ALTER TABLE %s ADD %s %s ( %s ) ;",
                            tableName,
                            getIndexType(indexInfo),
                            indexInfo.getPrimaryKey() ? "" : indexInfo.getIndexName(),
                            getIndexColumn(indexInfo.getIndexColumn())));
                    list.add(indexSql.toString());
                }

        );
        return list;
    }

    private String getIndexColumn(List<IndexInfo.IndexColumn> list) {
        StringBuilder sb = new StringBuilder();
        list.stream().sorted((Comparator.comparing(IndexInfo.IndexColumn::getOrdinalPosition))).forEach(v -> {
            sb.append("`" + v.getColumnName() + "`,");
        });
        sb.deleteCharAt(sb.length() - 1);
        return sb.toString();
    }

    private String getIndexType(IndexInfo indexInfo) {
        StringBuilder sb = new StringBuilder();
        if (indexInfo.getPrimaryKey()) {
            return " PRIMARY KEY ";
        }
        if (!indexInfo.getNonUnique()) {
            sb.append(" UNIQUE ");
        }
        sb.append(" INDEX ");
        return sb.toString();
    }

    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());
    }

    public List<ColumnInfo> getSourceColumn(String tableViewName, DatabaseMetaData metaData, String schemaPattern) throws SQLException {
        ResultSet rs = metaData.getColumns(null, schemaPattern, tableViewName, "%");
        List<ColumnInfo> sourceCloumn = new ArrayList<>();
        while (rs.next()) {
            ColumnInfo columnInfo = new ColumnInfo();

            columnInfo.setColumnComments(rs.getString("REMARKS"));
            columnInfo.setDataType(rs.getString("TYPE_NAME"));
            columnInfo.setColumnName(rs.getString("COLUMN_NAME"));
            columnInfo.setColumnSize(rs.getInt("COLUMN_SIZE"));
            columnInfo.setDecimalDigits(rs.getInt("DECIMAL_DIGITS"));
            columnInfo.setColumnType(SQLColumnTypeEnum.resolve(rs.getInt("DATA_TYPE")).getColumnEnum());
            //IS_NULLABLE - YES/NO  NULLABLE - 1(允许为空)/2(不确定)/0(不允许为空)
            columnInfo.setNullAbleStatus("yes".equalsIgnoreCase(rs.getString("IS_NULLABLE")) ? 1 : 0);
            sourceCloumn.add(columnInfo);
        }
        rs.close();
        return sourceCloumn;
    }
}
