package org.springblade.datasource.transform.general;

import lombok.extern.slf4j.Slf4j;
import org.springblade.datasource.transform.ColumnInfo;
import org.springblade.datasource.transform.IndexInfo;
import org.springblade.datasource.transform.TableInfo;
import org.springblade.etl.entity.bi.ReportDatasource;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author 喜欢番茄火锅
 * @date 2023/8/21 12:53
 */
@Slf4j
public class GeneralParseTableHandle {


    /**
     * 将源信息转换成通用表数据
     *
     * @param sourceDatasource
     * @param model
     * @param tableViewName
     * @param tableComment
     * @return {@link TableInfo}
     * @author 王瑞
     * @date 2023/8/16
     */
    public TableInfo parseTableInfo(ReportDatasource sourceDatasource, List<GeneralModel> model, String tableViewName, String tableComment) {


        TableInfo tableInfo = new TableInfo();
        tableInfo.setTableName(tableViewName);
        tableInfo.setTableComment(tableComment);
        tableInfo.setTableComment(tableComment);
        tableInfo.setColumnInfo(getColumnInfo(model, new ArrayList<>()));
        tableInfo.setIndexInfo(getIndexInfo(model));

        return tableInfo;

    }

    private List<ColumnInfo> getColumnInfo(List<GeneralModel> model, List<ColumnInfo> result) {

        model.stream().forEach(c -> {
            if (!c.getSourceColumn()) {
                ColumnInfo columnInfo = getColumnInfo(c);
                result.add(columnInfo);
            }
        });
        return result;
    }

    public ColumnInfo getColumnInfo(GeneralModel c) {
        ColumnInfo columnInfo = new ColumnInfo();
        columnInfo.setColumnComments(c.getColumnComments());
        columnInfo.setColumnName(c.getDestColumnName());
        columnInfo.setColumnSize(c.getColumnSize());
        columnInfo.setDecimalDigits(c.getDecimalDigits());
        columnInfo.setColumnType(GeneralEnum.valueOf(c.getType().toUpperCase()).getColumnEnum());
        return columnInfo;
    }

    public List<IndexInfo> getIndexInfo(List<GeneralModel> model) {

        return model.stream().filter(c -> !c.getSourceColumn()).filter(GeneralModel::getPrimaryKey).map(v -> {
            IndexInfo indexInfo = new IndexInfo();
            indexInfo.setIndexName("PRIMARY");
            indexInfo.setPrimaryKey(true);
            indexInfo.setNonUnique(true);
            List<IndexInfo.IndexColumn> indexColumns = new ArrayList<>();

            IndexInfo.IndexColumn indexColumn = indexInfo.new IndexColumn();
            indexColumn.setColumnName(v.getColumnName());
            indexColumn.setOrdinalPosition(0);
            indexColumn.setAscOrDesc("A");
            indexColumns.add(indexColumn);
            indexInfo.setIndexColumn(indexColumns);
            return indexInfo;
        }).collect(Collectors.toList());
    }

}
