package cn.axzo.msg.center.dal;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.annotation.IdType;
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.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.DateType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import org.apache.commons.lang3.StringUtils;

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

/**
 * 通用响应对象
 *
 * @author zhaoyong_sh
 * @see CodeGenerator
 * @since 2021-05-19 10:53
 */
public class CodeGenerator {

    public static String DRIVER_NAME = "com.mysql.jdbc.Driver";
//    public static String URL = "jdbc:mysql://rm-bp1qpff9er81dmgw7ko.mysql.rds.aliyuncs.com:3311/mns-dev?useUnicode=true&characterEncoding=utf8&allowMultiQueries=true&serverTimezone=GMT%2b8&useSSL=true&verifyServerCertificate=false";
//    public static String USERNAME = "mns";
//    public static String PASSWORD = "79AIDoSJjUb5oCaE";

    public static String URL = "jdbc:mysql://localhost:3306/test";
    public static String USERNAME = "carl";
    public static String PASSWORD = "123456";

    public static String SUPPER_MAPPER_CLASS = "com.baomidou.mybatisplus.core.mapper.BaseMapper";
    public static String BASE_PACKAGE = "cn.axzo.msg.notices.dao";
    public static String ENTITY_PACKAGE =  "entity";
    public static String MAPPER_PACKAGE =  "mapper";
    public static String SERVICE_PACKAGE =  "repository";
    public static String SERVICE_IMPL_PACKAGE = SERVICE_PACKAGE + ".impl";
    public static String CONTROLLER_PACKAGE = "";
    public static String PROJECT_PATH = System.getProperty("user.dir") + "/mns-dal";
    public static String MAPPER_OUT_PATH = PROJECT_PATH + "/src/main/resources/mapper";
    public static String PROJECT_RESOURCE_PATH = PROJECT_PATH + "/src/main/java";
    public static String MAPPER_XML_PACKAGE = PROJECT_PATH + "/src/main/resources/mapper";

    public static String AUTHOR = "szg";
    static String[] includeTables;
    static String[] excludeTables;

    static {
       // 做一些配置
    }

    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 + "！");
    }

    /**
     * 获取数据库配置
     * @return
     */
    public static DataSourceConfig dataSourceConfig() {
        return new DataSourceConfig()
                .setDbType(DbType.MYSQL)
                .setDriverName(DRIVER_NAME)
                .setUrl(URL)
                .setUsername(USERNAME)
                .setPassword(PASSWORD);
    }

    /**
     * 获取策略配置，哪些表需要生成，哪些不需要生成
     * @return
     */
    public static StrategyConfig strategyConfig() {
        return new StrategyConfig()
                .setTablePrefix("tb_")
                .setNaming(NamingStrategy.underline_to_camel) // 下划线转成驼峰命名
                .setColumnNaming(NamingStrategy.underline_to_camel)
                .setInclude(scanner("表名，多个以逗号分开：").split(","))
                .setExclude(excludeTables)
                .setSuperMapperClass(SUPPER_MAPPER_CLASS) // 继承的Mapper父类
                .setEntityBuilderModel(true) // 是否设置未Builder类
                .setEntityLombokModel(true)  // 是否Lombok类
                .setRestControllerStyle(true) // Controller 为 RestController 模式
                .setEntityTableFieldAnnotationEnable(true);
    }

    /**
     * 包配置(生成的Entity、Xml、Mapper、Controller、Service存放的问题)
     * @return
     */
    public static PackageConfig packageConfig() {
        return new PackageConfig()
                .setParent(BASE_PACKAGE)
                .setEntity(ENTITY_PACKAGE)
                .setController(CONTROLLER_PACKAGE)
                .setMapper(MAPPER_PACKAGE)
                .setService(SERVICE_PACKAGE)
                .setServiceImpl(SERVICE_IMPL_PACKAGE)
                ;
    }

    /**
     * 自动注入配置
     * @return
     */
    public static InjectionConfig injectionConfig() {

        return new InjectionConfig() {
            @Override
            public void initMap() {
//                Map<String, Object> map = new HashMap<String, Object>();
//                map.put("abc", this.getConfig().getGlobalConfig().getAuthor() + "-mp");
//                this.setMap(map);
            }
        }.setFileOutConfigList(
                Collections.<FileOutConfig>singletonList(new FileOutConfig("/templates/mapper.xml.vm") {
                    // 自定义输出文件目录
                    @Override
                    public String outputFile(TableInfo tableInfo) {
                        return MAPPER_OUT_PATH + "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
                    }
                })
        );
    }

    /**
     * 模板配置
     * 自定义模板配置，模板可以参考源码 /mybatis-plus/src/main/resources/template 使用 copy
     * 至您项目 src/main/resources/template 目录下，模板名称也可自定义如下配置：
     * @return
     */
    public static TemplateConfig templateConfig() {
        return new TemplateConfig()
                .setController("") // 不生成Controller类
                .setServiceImpl("templates/serviceimpl.java")
                .setXml(null); // 必须setXml(null)，不然会在项目目录下构建xml文件

    }

    /**
     * 全局配置
     * @return
     */
    public static GlobalConfig globalConfig() {
        return new GlobalConfig()
                .setOutputDir(PROJECT_RESOURCE_PATH)// 输出目录
                .setFileOverride(false)  // 是否覆盖文件
                .setActiveRecord(true)  // 开启 activeRecord 模式
                .setEnableCache(false)  // XML 二级缓存
                .setBaseResultMap(true) // XML ResultMap
                .setBaseColumnList(true)// XML columList
                .setDateType(DateType.ONLY_DATE)
                .setIdType(IdType.AUTO)
                .setAuthor(AUTHOR)
                .setEntityName("%s")
                .setXmlName("%sMapper")
                .setMapperName("%sMapper")
                .setServiceName("%sDao")
                .setServiceImplName("%sDaoImpl");
    }

    /**
     * 生成代码
     */
    public static void generate() {
        AutoGenerator autoGenerator = new AutoGenerator()
                .setGlobalConfig(globalConfig())
                .setDataSource(dataSourceConfig())
                .setStrategy(strategyConfig())
                .setPackageInfo(packageConfig())
                .setCfg(injectionConfig())
                .setTemplate(templateConfig())
                ;

        autoGenerator.execute();
    }

    public static void main(String[] args) {
        generate();
    }

}