package com.yeejoin.amos.boot.biz.common.utils;


import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.converts.MySqlTypeConvert;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.DbColumnType;
import com.baomidou.mybatisplus.generator.config.rules.IColumnType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
import org.apache.commons.lang.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

/**
 * @author DELL
 */
public class MyBatisPlusCodeGeneratorTzs {

    /**
     * 项目名称缩写
     */
    static String projectShortName = "tzs";
    /**
     * 拆分服务名   可根据实际拆分项目进行修改
     */
    static String ShortName = "tcm";

    /**
     * 项目api目录
     */
    static String apiAddress = "/amos-boot-system-" + projectShortName  + "/" + "amos-boot-module-" + ShortName + "/" +
            "amos-boot-module-" + ShortName + "-api/";

    /**
     * 项目biz目录
     */
    static String bizAddress = "/amos-boot-system-" + projectShortName + "/" + "amos-boot-module-" + ShortName + "/" +
            "amos-boot-module-" + ShortName + "-biz/";

    /**
     * 项目api路径
     */
    static String apiPath = apiAddress + "src/main/java/com/yeejoin/amos/boot/module/" + ShortName + "/api";

    /**
     * 项目biz路径
     */
    static String bizPath = bizAddress + "src/main/java/com/yeejoin/amos/boot/module/" + ShortName + "/biz";

    /**
     * 接口及实体等代码生成路径
     */
    static String interfaceCodeOutPath = System.getProperty("user.dir").replace("\\amos-boot-biz-common", "\\") + apiPath;


    /**
     * 控制器及接口实现等代码生成路径
     */
    static String controllerCodeOutPath = System.getProperty("user.dir").replace("\\amos-boot-biz-common", "\\") + bizPath;


    /**
     * 读取控制台内容
     */
    public static String scanner(String tip) {
        Scanner scanner = new Scanner(System.in);
        StringBuilder help = new StringBuilder();
        help.append("请输入" + tip + "：");
        System.out.println(help.toString());
        if (scanner.hasNext()) {
            String ipt = scanner.next();
            if (StringUtils.isNotEmpty(ipt)) {
                return ipt;
            }
        }
        throw new MybatisPlusException("请输入正确的" + tip + "！");
    }

    public static void main(String[] args) {
        // 代码生成器
        AutoGenerator autoGenerator = new AutoGenerator();

        // 全局配置
        GlobalConfig gc = new GlobalConfig();
        // 工程路径-最外层
        final String projectPath = System.getProperty("user.dir").replace("\\amos-boot-biz-common", "\\");
        System.out.println("projectPath:"+projectPath);
        // 代码输出目录
        //gc.setOutputDir(codeOutPath);
        // 作者
        gc.setAuthor("system_generator");
        // 是否自动打开文件夹 建议开启
        gc.setOpen(false);
        // 开启Swagger2 注解支持
        gc.setSwagger2(true);
        // 注入autoGenerator
        autoGenerator.setGlobalConfig(gc);

        gc.setActiveRecord(false);
        // 数据源配置
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setUrl("jdbc:postgresql://172.16.10.243:5432/tzs_amos_tzs_biz_init?&serverTimezone=GMT%2B8");
        dsc.setSchemaName("amos_tzs_biz");
        dsc.setDriverName("org.postgresql.Driver");
//        dsc.setDriverName("cn.com.vastbase.Driver");
        dsc.setUsername("admin");
        dsc.setPassword("Yeejoin@2023");

        dsc.setTypeConvert(new ITypeConvert() {
            @Override
            public IColumnType processTypeConvert(GlobalConfig globalConfig, String fieldType) {
                String t = fieldType.toLowerCase();
                if (t.contains("datetime")) {
                    return DbColumnType.DATE;
                }
                if (t.contains("date")) {
                    return DbColumnType.DATE;
                }
                //其它字段采用默认转换（非mysql数据库可以使用其它默认的数据库转换器）
                return new MySqlTypeConvert().processTypeConvert(globalConfig, fieldType);
            }
        });

        autoGenerator.setDataSource(dsc);

        // 包配置
        final PackageConfig pc = new PackageConfig();
        // 填写对应模块
        pc.setModuleName(ShortName);
        // 实体路径
        pc.setParent("com.yeejoin.amos.boot.module");
        pc.setEntity("api.entity");
        pc.setMapper("api.mapper");
        pc.setService("api.service");
        pc.setServiceImpl("biz.service.impl");
        pc.setController("biz.controller");
        pc.setXml("api.dto");
        autoGenerator.setPackageInfo(pc);

        // 自定义配置
        InjectionConfig cfg = new InjectionConfig() {
            @Override
            public void initMap() {
                // to do nothing
            }
        };
        // 如果模板引擎是 freemarker
        String controller = "/template/controller.java.ftl";
        String entity = "/template/bean.java.ftl";
        String mapper = "/template/mapper.java.ftl";
        String service = "/template/service.java.ftl";
        String serviceImpl = "/template/serviceImpl.java.ftl";
        String mapperXml = "/template/mapper.xml.ftl";
        String dto = "/template/dto.java.ftl";
        String vo = "/template/vo.java.ftl";


        // 自定义配置会被优先输出
        List<FileOutConfig> focList = new ArrayList<>();
        focList.add(new FileOutConfig(controller) {
            @Override
            public String outputFile(TableInfo tableInfo) {
                String filePath = controllerCodeOutPath
                        + "/controller/" + tableInfo.getControllerName() + StringPool.DOT_JAVA;
                System.out.println("controller:"+filePath);
                return filePath;
            }
        });

        focList.add(new FileOutConfig(entity) {
            @Override
            public String outputFile(TableInfo tableInfo) {
                String filePath = interfaceCodeOutPath
                        + "/entity/" + tableInfo.getEntityName() + StringPool.DOT_JAVA;
                System.out.println("entity:"+filePath);
                return filePath;
            }
        });


        focList.add(new FileOutConfig(dto) {
            @Override
            public String outputFile(TableInfo tableInfo) {
                String filePath = interfaceCodeOutPath
                        + "/dto/" + tableInfo.getEntityName() + "Dto" + StringPool.DOT_JAVA;
                System.out.println("dto:"+filePath);
                return filePath;
            }
        });

//        focList.add(new FileOutConfig(vo) {
//            @Override
//            public String outputFile(TableInfo tableInfo) {
//                String filePath = interfaceCodeOutPath
//                        + "/vo/" + tableInfo.getEntityName() + "Vo" + StringPool.DOT_JAVA;
//                System.out.println("vo:"+filePath);
//                return filePath;
//            }
//        });

        focList.add(new FileOutConfig(mapper) {
            @Override
            public String outputFile(TableInfo tableInfo) {
                String filePath = interfaceCodeOutPath
                        + "/mapper/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_JAVA;
                System.out.println("mapper:"+filePath);
                return filePath;
            }
        });

        focList.add(new FileOutConfig(service) {
            @Override
            public String outputFile(TableInfo tableInfo) {
                String filePath = interfaceCodeOutPath
                        + "/service/" + tableInfo.getServiceName() + StringPool.DOT_JAVA;
                System.out.println("service:"+filePath);
                return filePath;
            }
        });

        focList.add(new FileOutConfig(serviceImpl) {
            @Override
            public String outputFile(TableInfo tableInfo) {
                String filePath = controllerCodeOutPath
                        + "/service/impl/" + tableInfo.getServiceImplName() + StringPool.DOT_JAVA;
                System.out.println("service/impl:"+filePath);
                return filePath;
            }
        });


//        focList.add(new FileOutConfig(mapperXml) {
//            @Override
//            public String outputFile(TableInfo tableInfo) {
//                // 自定义输出文件名 ， 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化！！
//                return projectPath + projectName + "src/main/resources/mapper/" + pc.getModuleName()
//                        + "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
//            }
//        });
        focList.add(new FileOutConfig(mapperXml) {
            @Override
            public String outputFile(TableInfo tableInfo) {
                // 自定义输出文件名 ， 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化！！
                String filePath =  projectPath + apiAddress + "src/main/resources/mapper/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
                System.out.println("mapper:"+filePath);
                return filePath;
            }
        });

        /*
        cfg.setFileCreate(new IFileCreate() {
            @Override
            public boolean isCreate(ConfigBuilder configBuilder, FileType fileType, String filePath) {
                // 判断自定义文件夹是否需要创建
                checkDir("调用默认方法创建的目录");
                return false;
            }
        });
        */
        cfg.setFileOutConfigList(focList);
        autoGenerator.setCfg(cfg);

        // 配置模板
        TemplateConfig templateConfig = new TemplateConfig();

        // 配置自定义输出模板
        //指定自定义模板路径，注意不要带上.ftl/.vm, 会根据使用的模板引擎自动识别
        // templateConfig.setEntity("templates/entity2.java");
        // templateConfig.setService();
        // templateConfig.setController();

        templateConfig.setXml(null);
        autoGenerator.setTemplate(templateConfig);

        // 策略配置
        StrategyConfig strategy = new StrategyConfig();
        strategy.setNaming(NamingStrategy.underline_to_camel);
        strategy.setColumnNaming(NamingStrategy.underline_to_camel);
        strategy.setSuperEntityClass("com.yeejoin.amos.boot.biz.common.entity.BaseEntity");
        strategy.setEntityLombokModel(true);
        strategy.setRestControllerStyle(true);
        // 公共父类-开启将导致swagger无效化
        //strategy.setSuperControllerClass("com.test.base.BaseController");
        // 写于父类中的公共字段
        strategy.setSuperEntityColumns("sequence_nbr", "rec_date", "rec_user_id", "rec_user_name",
                "is_delete");
        // 建议以后开启
        strategy.setInclude(scanner("表名，多个英文逗号分割").split(","));
        strategy.setControllerMappingHyphenStyle(true);
        strategy.setTablePrefix();
        //去除表名前缀
        //去除表名前缀
        strategy.setTablePrefix("t_", "tb_", "sys_","other_", "rpm_", "s_", "tcb_", "cb_", "tz_", "jc_", "jcb_");
        // 设置父级Controller
        strategy.setSuperControllerClass("com.yeejoin.amos.boot.biz.common.controller.BaseController");
        autoGenerator.setStrategy(strategy);
        autoGenerator.setTemplateEngine(new FreemarkerTemplateEngine());
        autoGenerator.execute();
    }

}