package com.sunxung.factoring.generator;


import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
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 java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

/**
 * @author 大仙
 * mybatis plus code generator
 */
public class MpCodeGenerator {


    //模块名称(重要，需要根据功能模块名称修改)
    public static final String moduleName = "sys";
    //author
    public static final String author = "liutao";
    //database
    public static final String databaseUrl = "jdbc:mysql://192.168.3.6:3106/factoring_trade_v4?characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghai&rewriteBatchedStatements=true";
    public static final String driverName = "com.mysql.jdbc.Driver";
    public static final String userName = "root";
    public static final String password = "root";


    //输出文件相对路径
    public static final String outPutDir = "/src/test/resources";
    //包路径(重要，需要根据模块包路径修改)
    public static final String packageName = "com.sunxung.factoring";
    /**
     * 使用步骤：
     * 1.修改包路径，模块名称，生成人信息
     * 2.修改database数据库连接信息
     * 3.运行main方法
     * 4.控制台输入生成文件的表名
     * 5.生成的文件位于：
     *      dev-tools模块>test>java
     *      dev-tools模块>test>resources
     * @param args
     */
    public static void main(String[] args) {

        AutoGenerator mpg = new AutoGenerator();

        // 全局配置
        GlobalConfig gc = new GlobalConfig();
        String projectPath = System.getProperty("user.dir");
        gc.setOutputDir(projectPath + outPutDir);
        gc.setAuthor(author);
        gc.setOpen(false);
        gc.setActiveRecord(false);
        //覆盖文件
        //gc.setFileOverride(true);
        gc.setBaseResultMap(true);
        gc.setIdType(IdType.ASSIGN_ID);
        mpg.setGlobalConfig(gc);

        // 数据源配置
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setUrl(databaseUrl);
        dsc.setDriverName(driverName);
        dsc.setUsername(userName);
        dsc.setPassword(password);
        //自定义时间转换为Date，默认为LocalDateTime
        dsc.setTypeConvert(new ITypeConvert() {
            @Override
            public IColumnType processTypeConvert(GlobalConfig globalConfig, String fieldType) {
                String t = fieldType.toLowerCase();
                if(t.contains("datetime")){
                    return DbColumnType.DATE;
                }
                return new MySqlTypeConvert().processTypeConvert(globalConfig,fieldType);
            }
        });
        mpg.setDataSource(dsc);

        // 包配置
        PackageConfig pc = new PackageConfig();
        //pc.setModuleName(moduleName);
        pc.setParent(packageName);
        pc.setController("web."+moduleName);
        pc.setService("service."+moduleName);
        pc.setServiceImpl("service."+moduleName+".impl");
        pc.setEntity("entity."+moduleName);
        pc.setMapper("mapper."+moduleName);
        mpg.setPackageInfo(pc);

        // 自定义配置
        InjectionConfig cfg = new InjectionConfig() {
            @Override
            public void initMap() {
            }
        };
        List<FileOutConfig> focList = new ArrayList<>();
        focList.add(new FileOutConfig("/templates/mapper.xml.ftl") {
            @Override
            public String outputFile(TableInfo tableInfo) {
                // 自定义输入文件名称
                return projectPath + "/src/test/resources/mapper/"+moduleName+"/"
                        + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
            }
        });
        cfg.setFileOutConfigList(focList);
        mpg.setCfg(cfg);
        mpg.setTemplate(new TemplateConfig().setXml(null));

        // 策略配置
        StrategyConfig strategy = new StrategyConfig();
        strategy.setNaming(NamingStrategy.underline_to_camel);
        strategy.setColumnNaming(NamingStrategy.underline_to_camel);
        strategy.setSuperEntityClass("com.sunxung.factoring.entity.BaseEntity");
        strategy.setEntityLombokModel(true);
        strategy.setInclude(scanner("表名").toUpperCase());
        strategy.setControllerMappingHyphenStyle(true);
        strategy.setTablePrefix(pc.getModuleName() + "_");
        strategy.setRestControllerStyle(false);
        strategy.setEntityLombokModel(false);
        strategy.setEntityTableFieldAnnotationEnable(true);
//        strategy.setSuperEntityColumns("id","create_user_id","create_user_name",
//                "create_time","update_user_name","update_user_id",
//                "update_time","delete_flag","version","tenant_id");
        mpg.setStrategy(strategy);
        // 选择 freemarker 引擎需要指定如下加，注意 pom 依赖必须有！
        mpg.setTemplateEngine(new FreemarkerTemplateEngine());
        mpg.execute();
    }


    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.isNotBlank(ipt)) {
                return ipt;
            }
        }
        throw new MybatisPlusException("请输入正确的" + tip + "！");
    }



}
