package cn.meowrain.aioj.generator;

import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.generator.FastAutoGenerator;
import com.baomidou.mybatisplus.generator.config.OutputFile;
import com.baomidou.mybatisplus.generator.config.rules.DateType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
import com.baomidou.mybatisplus.generator.fill.Column;

import java.util.Collections;
import java.util.Scanner;

/**
 * 交互式代码生成器
 * <p>
 * 运行后会在控制台提示输入相关配置信息
 * </p>
 * <p>
 * 生成规则：
 * - Entity: XxxDO (数据对象)
 * - Controller: /v1/xxx (RESTful 风格，包含 CRUD)
 * </p>
 *
 * @author meowrain
 * @since 1.0.0
 */
public class InteractiveCodeGenerator {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        System.out.println("========== AIOJ 代码生成器 ==========");
        System.out.println();

        // 数据库配置
        System.out.print("请输入数据库地址 (默认: localhost:3306/aioj): ");
        String dbHost = scanner.nextLine().trim();
        if (dbHost.isEmpty()) {
            dbHost = "localhost:3306/aioj";
        }
        String dbUrl = "jdbc:mysql://" + dbHost + "?useUnicode=true&characterEncoding=utf8&serverTimezone=Asia/Shanghai";

        System.out.print("请输入数据库用户名 (默认: root): ");
        String dbUsername = scanner.nextLine().trim();
        if (dbUsername.isEmpty()) {
            dbUsername = "root";
        }

        System.out.print("请输入数据库密码: ");
        String dbPassword = scanner.nextLine().trim();

        // 代码配置
        System.out.print("请输入模块名 (如 userservice, questionservice): ");
        String moduleName = scanner.nextLine().trim();

        System.out.print("请输入要生成的表名 (多个表用逗号分隔): ");
        String tableInput = scanner.nextLine().trim();
        String[] tableNames = tableInput.split(",");

        System.out.print("请输入表前缀 (如 sys_,t_ 留空则不去除前缀): ");
        String prefixInput = scanner.nextLine().trim();
        String[] tablePrefixes = prefixInput.isEmpty() ? new String[]{} : prefixInput.split(",");

        System.out.print("请输入输出目录 (留空使用当前目录): ");
        String outputDir = scanner.nextLine().trim();
        if (outputDir.isEmpty()) {
            outputDir = System.getProperty("user.dir") + "/src/main/java";
        }

        String mapperXmlDir = outputDir.replace("/java", "/resources") + "/mapper";

        System.out.println();
        System.out.println("========== 配置确认 ==========");
        System.out.println("数据库: " + dbUrl);
        System.out.println("模块名: " + moduleName);
        System.out.println("表名: " + String.join(", ", tableNames));
        System.out.println("输出目录: " + outputDir);
        System.out.println();
        System.out.print("确认生成? (y/n): ");

        String confirm = scanner.nextLine().trim().toLowerCase();
        if (!confirm.equals("y") && !confirm.equals("yes")) {
            System.out.println("已取消生成");
            return;
        }

        // 执行生成
        generate(dbUrl, dbUsername, dbPassword, moduleName, tableNames, tablePrefixes, outputDir, mapperXmlDir);

        scanner.close();
    }

    private static void generate(String dbUrl, String dbUsername, String dbPassword,
                                  String moduleName, String[] tableNames, String[] tablePrefixes,
                                  String outputDir, String mapperXmlDir) {
        FastAutoGenerator.create(dbUrl, dbUsername, dbPassword)
                // 全局配置
                .globalConfig(builder -> builder
                        .author("meowrain")
                        .outputDir(outputDir)
                        .dateType(DateType.TIME_PACK)
                        .commentDate("yyyy-MM-dd")
                        .disableOpenDir()
                )
                // 包配置
                .packageConfig(builder -> builder
                        .parent("cn.meowrain.aioj.backend")
                        .moduleName(moduleName)
                        .entity("dao.entity")
                        .mapper("dao.mapper")
                        .service("service")
                        .serviceImpl("service.impl")
                        .controller("controller")
                        .xml("mapper")
                        .pathInfo(Collections.singletonMap(OutputFile.xml, mapperXmlDir))
                )
                // 策略配置
                .strategyConfig(builder -> {
                    builder.addInclude(tableNames);
                    if (tablePrefixes.length > 0) {
                        builder.addTablePrefix(tablePrefixes);
                    }
                    builder
                            // Entity 策略: 生成 XxxDO
                            .entityBuilder()
                            .formatFileName("%sDO")  // 实体类后缀改为 DO
                            .enableLombok()
                            .enableTableFieldAnnotation()
                            .naming(NamingStrategy.underline_to_camel)
                            .columnNaming(NamingStrategy.underline_to_camel)
                            .idType(IdType.ASSIGN_ID)
                            .addTableFills(new Column("create_time", FieldFill.INSERT))
                            .addTableFills(new Column("update_time", FieldFill.INSERT_UPDATE))
                            .logicDeleteColumnName("del_flag")
                            .logicDeletePropertyName("delFlag")
                            // Mapper 策略
                            .mapperBuilder()
                            .enableBaseResultMap()
                            .enableBaseColumnList()
                            // Service 策略
                            .serviceBuilder()
                            .formatServiceFileName("%sService")
                            .formatServiceImplFileName("%sServiceImpl")
                            // Controller 策略
                            .controllerBuilder()
                            .enableRestStyle();
                })
                // 自定义模板 (使用 /templates/ 目录下的模板)
                .templateConfig(builder -> builder
                        .entity("/templates/entityDO.java")
                        .controller("/templates/controller.java")
                        .service("/templates/service.java")
                        .serviceImpl("/templates/serviceImpl.java")
                        .mapper("/templates/mapper.java")
                        .xml("/templates/mapper.xml")
                )
                // 模板引擎
                .templateEngine(new FreemarkerTemplateEngine())
                .execute();

        System.out.println();
        System.out.println("========== 代码生成完成 ==========");
        System.out.println("Java 代码: " + outputDir);
        System.out.println("Mapper XML: " + mapperXmlDir);
        System.out.println();
        System.out.println("生成规则:");
        System.out.println("  - Entity: XxxDO");
        System.out.println("  - Controller: /v1/xxx (包含 CRUD 增删改查)");
    }
}
