
package com.lideeyunji.tool.framework.sql.build.build.ddl;

import com.lideeyunji.tool.framework.sql.build.ISQLExpression;
import com.lideeyunji.tool.framework.sql.build.buildmodel.SQLInterpretContext;
import com.lideeyunji.tool.framework.sql.build.buildmodel.ddl.SqlInfoCreateIndexModel;
import com.lideeyunji.tool.framework.sql.entity.DbColunmTypesEntity;
import com.lideeyunji.tool.framework.sql.utils.PlusUtils;
import com.lideeyunji.tool.framework.sql.core.model.SqlFormatModel;
import com.lideeyunji.tool.framework.yunji.utils.FuncBase;
import net.sf.jsqlparser.JSQLParserException;

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

/***
 * 索引相关
 */
public class BuildCreateIndex implements ISQLExpression<List<SqlFormatModel>> {



    @Override
    public List<SqlFormatModel> interpret(SQLInterpretContext context) throws JSQLParserException {
        SqlInfoCreateIndexModel model = context.getCreateIndexModel();
        DbColunmTypesEntity dbColunmTypes = context.getDbColunmTypes();
        if(FuncBase.isEmpty(model)){
            return null;
        }
        //存在自定义ddl
        List<String> executeDdlList = model.getExecuteDdlList();
        if(FuncBase.isNotEmpty(executeDdlList)){
            return PlusUtils.ddl2SqlFormatModel(executeDdlList);
        }

        String symbol = dbColunmTypes.getSymbol();
        Boolean upperFlag = dbColunmTypes.getUpperFlag();

        String tableName = FuncBase.concatSymbol(model.getTableName(),symbol,upperFlag);
        String indexName = FuncBase.concatSymbol(model.getIndexName(),symbol,upperFlag);
        String indexType = model.getIndexType();
        String schemaName = FuncBase.concatSymbol(context.getSchemaName(),symbol);


        List<String> indexFieldCodeList = model.getIndexFieldCodeList();

        List<String> list = indexFieldCodeList.stream()
                .map(key -> FuncBase.concatSymbol( key , symbol,upperFlag))
                .collect(Collectors.toList());

        String str = "CREATE INDEX %s ON %s.%s (%s)";
        if(FuncBase.isNotEmpty(indexType) && "UNIQUE".equals(indexType.toUpperCase())){//唯一
            str = "CREATE UNIQUE INDEX %s ON %s.%s (%s)";
        }

        String ddl = String.format(str, indexName, schemaName,tableName, String.join(",", list));

        return PlusUtils.ddl2SqlFormatModel(ddl);


    }

}
