package com.ema.admin.codegen;

import cn.hutool.core.util.ArrayUtil;
import com.mybatisflex.annotation.KeyType;
import com.mybatisflex.codegen.Generator;
import com.mybatisflex.codegen.config.ColumnConfig;
import com.mybatisflex.codegen.config.GlobalConfig;
import com.mybatisflex.core.keygen.KeyGenerators;
import com.ema.common.domain.base.BaseEntity;
import com.zaxxer.hikari.HikariDataSource;

/**
 * MybatisFlex代码生成器
 */
public class MybatisFlexCodegen {

        public static void main(String[] args) {
            //配置数据源
            HikariDataSource dataSource = new HikariDataSource();
            dataSource.setJdbcUrl("jdbc:mysql://172.16.0.212:3306/ema_projet?useUnicode=true&characterEncoding=UTF-8&&serverTimezone=GMT%2B8&allowMultiQueries=true&nullCatalogMeansCurrent=true");
            dataSource.setUsername("root");
            dataSource.setPassword("Xcsz@2024");
            String module = "assets";
            String[] tables = {"assets_info","asset_status_history"};

            //创建全局配置
            GlobalConfig globalConfig = createGlobalConfigUseStyle(module, tables);
            //通过 datasource 和 globalConfig 创建代码生成器
            Generator generator = new Generator(dataSource, globalConfig);
            //生成代码
            generator.generate();
        }

        /**
         * 创建全局配置
         * @param module 模块名称
         * @param tables 表名称 null 表示生成所有表
         * @return
         */
        public static GlobalConfig createGlobalConfigUseStyle(String module, String[] tables) {
            //创建配置内容
            GlobalConfig globalConfig = new GlobalConfig();

            globalConfig.setBasePackage("com.ema.admin.modules."+module);
            if(ArrayUtil.isNotEmpty(tables)){
                //设置表前缀和只生成哪些表
                //globalConfig.setTablePrefix("g_");
                globalConfig.setGenerateTable(tables);
            }

            //设置生成 entity 并启用 Lombok 和 Swagger
            globalConfig.setEntitySuperClass(BaseEntity.class);
            globalConfig.setEntityGenerateEnable(true);
            globalConfig.setEntityWithLombok(true);
            globalConfig.setEntityWithSwagger(true);

            //设置生成 mapper
            globalConfig.setMapperGenerateEnable(true);
            globalConfig.setServiceGenerateEnable(true);
            globalConfig.setServiceImplGenerateEnable(true);
            globalConfig.setMapperXmlGenerateEnable(true);
            globalConfig.setControllerGenerateEnable(true);
            //globalConfig.setTableDefGenerateEnable(true);

            //可以单独配置某个列
            ColumnConfig columnConfig = new ColumnConfig();
            columnConfig.setColumnName("id");
            columnConfig.setKeyType(KeyType.Generator);
            columnConfig.setKeyValue(KeyGenerators.snowFlakeId);
            globalConfig.setColumnConfig(columnConfig);

            return globalConfig;
        }

    }
