package com.ag.mybatisplusgenerator.base;

import com.ag.mybatisplusgenerator.config.DateTypeConvertHandler;
import com.ag.mybatisplusgenerator.config.GeneratorConfig;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.config.*;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;

public class BaseGenerator {

    //生成策略
    private final StrategyConfig.Builder STRATEGY_CONFIG = GeneratorConfig.getSTRATEGY_CONFIG();

    private final TemplateConfig TEMPLATE_CONFIG = GeneratorConfig.getTemplateConfig();

    private final PackageConfig.Builder PACKAGE_CONFIG = GeneratorConfig.getPACKAGE_CONFIG();

    private final AutoGenerator generator;

    public BaseGenerator(String dataSourceUrl, String user, String password, String schema, String parent, String project) {
        DataSourceConfig.Builder builder = new DataSourceConfig
                .Builder(dataSourceUrl, user, password)
                .typeConvertHandler(new DateTypeConvertHandler(GeneratorConfig.getGlobalConfig(project).build()));
        if (!StringUtils.isEmpty(schema)) {
            builder.schema(schema);
        }
        generator = new AutoGenerator(builder.build());


        generator.global(GeneratorConfig.getGlobalConfig(project).build());

        //自定义xml位置
        Map<OutputFile, String> pathInfo = new HashMap<>();
        String parentProjectSrc = System.getProperty("user.dir");
        String srcBase = "\\src\\main\\resources\\mapper";
        String src = parentProjectSrc.substring(0, parentProjectSrc.lastIndexOf("\\") + 1) + project + srcBase;
        pathInfo.put(OutputFile.xml, src);
        generator.packageInfo(PACKAGE_CONFIG.parent(parent)
                .pathInfo(pathInfo)
                .build());


        generator.template(TEMPLATE_CONFIG);
    }

    public void run(String... tableNames) {
        generator.strategy(STRATEGY_CONFIG.addInclude(tableNames).build());
        generator.execute();
    }
}
