package top.continew.admin.utils;

import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableName;
import com.baomidou.mybatisplus.generator.FastAutoGenerator;
import com.baomidou.mybatisplus.generator.config.OutputFile;
import com.baomidou.mybatisplus.generator.config.rules.DbColumnType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
import com.baomidou.mybatisplus.generator.fill.Column;
import org.apache.commons.lang3.ClassUtils;

import java.io.File;
import java.sql.Types;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

/**
 * @author zoutao
 * @date 2023/09/13
 */
public class MyGenerator {

    //数据库连接信息
    static String url = "jdbc:mysql://192.168.241.129:3306/continew?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=Asia/Shanghai",
            username = "continew",
            password = "continew123456";

    // 设置作者
    static String author = "xudm";
    // 指定输出目录
    static String outputDir = "D:\\DevelopmentSpace\\MyWorkSpace\\OutPutDir\\coin-core";

    // 设置父包名
    static String parent = "top.continew.admin";
    // 表前缀
    static String[] tablePrefix = {"t_", "b_"};
    // 字段前缀
    static String[] fieldPrefix = {"f_"};
    //自动填充字段
    static Column[] fillColumns = new Column[]{
            new Column("f_updated_time", FieldFill.INSERT_UPDATE),
            new Column("f_created_time", FieldFill.INSERT),
            new Column("f_corp_id", FieldFill.INSERT),
            new Column("f_corp_name", FieldFill.INSERT),
            new Column("f_created_user_business_id", FieldFill.INSERT),
            new Column("f_created_user_name", FieldFill.INSERT),
            new Column("f_updated_user_business_id", FieldFill.INSERT_UPDATE),
            new Column("f_updated_user_name", FieldFill.INSERT_UPDATE),
            new Column("f_delete_flag", FieldFill.INSERT),
            new Column("f_status", FieldFill.INSERT),
    };


    public static void main(String[] args) {
        // 项目名 例如app  web
        generatorByBusinessModule("coin", new String[]{"b_invite_rewards_fetch_record", "b_invite_rewards_rule"});
    }

    /**
     * @param businessModuleName 业务模块名称，可以为空
     * @param generatorTables    需要生成的表名称
     */
    private static void generatorByBusinessModule(String businessModuleName, String[] generatorTables) {


        //设置 entity 包名
        String entityPackageName = businessModuleName + ".model.entity";
        //设置 controller 包名
        String controllerPackageName = businessModuleName + ".controller";
        //设置 service 包名
        String servicePackageName = businessModuleName + ".service";
        //设置 serviceImpl 包名
        String serviceImplPackageName = businessModuleName + ".service.Impl";
        //设置 mapper 包名
        String mapperPackageName = businessModuleName + ".mapper";

        // 设置mapperXml生成路径
        String mapperXmlPath = outputDir + "/mapper/";

        // 设置 service 父类
        String superServiceName = "com.baomidou.mybatisplus.extension.service.IService";
        // 设置 serviceImpl 父类
        String superServiceImplName = "com.baomidou.mybatisplus.extension.service.impl.ServiceImpl";

        FastAutoGenerator.create(url, username, password)
                .globalConfig(builder -> {
                    builder.author(author)
                            .outputDir(outputDir);
                })
                .dataSourceConfig(builder -> builder.typeConvertHandler((globalConfig, typeRegistry, metaInfo) -> {
                    int typeCode = metaInfo.getJdbcType().TYPE_CODE;
                    if (typeCode == Types.SMALLINT) {
                        // 自定义类型转换
                        return DbColumnType.INTEGER;
                    }
                    if (typeCode == Types.BIGINT) {
                        return DbColumnType.STRING;
                    }
                    if (typeCode == Types.TINYINT) {
                        return DbColumnType.INTEGER;
                    }
                    return typeRegistry.getColumnType(metaInfo);

                }))

                .packageConfig(builder -> {
                    builder.entity(entityPackageName)
                            .controller(controllerPackageName)
                            .mapper(mapperPackageName)
                            .service(servicePackageName)
                            .serviceImpl(serviceImplPackageName)
                            .parent(parent) // 设置父包名
                            .pathInfo(Collections.singletonMap(OutputFile.xml, mapperXmlPath)); // 设置mapperXml生成路径
                })
                .strategyConfig(builder -> {

                    builder.controllerBuilder()
                            .enableFileOverride()
                            .enableRestStyle();

                    builder.serviceBuilder()
                            .enableFileOverride()
                            .superServiceClass(superServiceName)
                            .superServiceImplClass(superServiceImplName)
                            .build();

                    builder.mapperBuilder()
                            .enableBaseColumnList()
                            .enableBaseResultMap()
                            .enableFileOverride();
                    builder.entityBuilder()
                            .addTableFills(fillColumns)
                            .enableFileOverride()
                            .enableLombok()
                            .idType(IdType.ASSIGN_ID) // 主键类型，生成策略
                            .enableTableFieldAnnotation()
                            .naming(NamingStrategy.underline_to_camel)
                            .disableSerialVersionUID()
                            .enableActiveRecord();// 开启 ActiveRecord 模式
                    builder
                            .addInclude(generatorTables)
                            .addTablePrefix(tablePrefix)// 设置过滤表前缀
                            .addFieldPrefix(fieldPrefix)
                    ;
                }).templateEngine(new FreemarkerTemplateEngine())
                .execute();
    }

    static class ModuleTableGenerator {
        public static Map<String, String[]> moduleTablesMap = new HashMap<>();

        static {
            moduleTablesMap.put("user", new String[]{"t_cmttg_human_role", "t_human_user", "t_test_user", "t_cmttg_user_basic", "t_cmttg_user_business", "t_cmttg_user_business_rel", "t_cmttg_user_platform"});
            moduleTablesMap.put("role", new String[]{"t_cmttg_role_inc", "t_cmttg_role_type", "t_cmttg_role_type_rel", "t_cmttg_sys_role"});

            moduleTablesMap.put("center", new String[]{"t_human_dept", "t_cmttg_human_org",
                    "t_human_position", "t_cmttg_sys_base_org", "t_cmttg_sys_base_org_region",
                    "t_cmttg_sys_base_org_role", "t_cmttg_sys_org", "t_cmttg_sys_org_role"
            });
            moduleTablesMap.put("menu", new String[]{"t_cmttg_app_info", "t_cmttg_app_menu", "t_cmttg_role_app_menu", "t_cmttg_role_web_menu", "t_cmttg_user_app_menu", "t_cmttg_user_web_menu", "t_cmttg_web_menu"
            });
            moduleTablesMap.put("system", new String[]{"t_cmttg_dict", "t_cmttg_sys_region",
            });
        }


        private static void getFileTableNames() throws ClassNotFoundException {
            String moduleName = "system";
            String path = "C:\\Users\\Administrator\\IdeaProjects\\cmttg\\cmttg-common\\src\\main\\java\\com\\xwtec\\cmttg\\common\\pojo\\" + moduleName;

            String packageName = "com.xwtec.cmttg.common.pojo." + moduleName;
            File file = new File(path);
            for (File listFile : file.listFiles()) {
                String className = packageName + "." + listFile.getName().replace(".java", "");
                Class<?> aClass = ClassUtils.getClass(className);
                TableName annotation = aClass.getAnnotation(TableName.class);
                System.err.print(",\"" + annotation.value() + "\"");
            }
        }

    }
}
