package com.yh.saas.plugin.clouddisk;

import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.builder.ConfigBuilder;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.DbType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;

import java.io.File;
import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

/**
 * 生成代码
 *
 * @author SunTianjun
 */
public class GeneratorCodeByTables {

    private static final String DATA_SOURCE_PREFIX = "spring.datasource.";

    private static final String DATA_SOURCE_URL = "jdbc:mysql://192.168.26.6:3306/winsea_zjcc?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull&allowMultiQueries=true&useSSL=false&serverTimezone=UTC";

    private static final String DATA_SOURCE_USERNAME = "root";

    private static final String DATA_SOURCE_CIPHER_CODE = "yinghai.2019";

    private static final String DATA_SOURCE_DRIVER_CLASS_NAME = "com.mysql.cj.jdbc.Driver";

    private static Properties properties;

    static {
        try {
            properties = new Properties();
            properties.put(DATA_SOURCE_PREFIX + "url", DATA_SOURCE_URL);
            properties.put(DATA_SOURCE_PREFIX + "username", DATA_SOURCE_USERNAME);
            properties.put(DATA_SOURCE_PREFIX + "password", DATA_SOURCE_CIPHER_CODE);
            properties.put(DATA_SOURCE_PREFIX + "driver-class-name", DATA_SOURCE_DRIVER_CLASS_NAME);
        } catch (Exception e) {


        }
    }

    public static void main(String[] args) throws IOException {
        generateByTables("SongJin", "com.yh.saas.plugin.oil", "oil_analysis_report_info");
    }

    /**
     * 通过表生成类
     *
     * @param author      作者
     * @param packageName 包名
     * @param tableNames  表名，不传创建所有
     * @throws IOException
     */
    private static void generateByTables(String author, String packageName, String... tableNames) throws IOException {
        GlobalConfig config = new GlobalConfig();

        String dbUrl = properties.getProperty(DATA_SOURCE_PREFIX + "url");
        String dbUsername = properties.getProperty(DATA_SOURCE_PREFIX + "username");
        String dbPassword = properties.getProperty(DATA_SOURCE_PREFIX + "password");
        String dbDriverName = properties.getProperty(DATA_SOURCE_PREFIX + "driver-class-name");

        DataSourceConfig dataSourceConfig = new DataSourceConfig();
        dataSourceConfig.setDbType(DbType.MYSQL).setUrl(dbUrl).setUsername(dbUsername).setPassword(dbPassword)
                .setDriverName(dbDriverName);
        StrategyConfig strategyConfig = new StrategyConfig();
        strategyConfig.setEntityLombokModel(true)
                .setSuperEntityColumns("create_date", "create_user_id", "update_date", "update_user_id", "update_flag",
                        "delete_flag", "update_count", "now_version_no", "prev_version_no")
                .setSuperEntityClass("BaseModel").setRestControllerStyle(true).setCapitalMode(true)
                .setDbColumnUnderline(true).setNaming(NamingStrategy.underline_to_camel).setInclude(tableNames);// 修改替换成你需要的表名，多个表名传数组
        config.setActiveRecord(true).setAuthor(author).setOutputDir(new File("src/main/java").getCanonicalPath())
                .setFileOverride(false).setEnableCache(false);

        TemplateConfig templateConfig = new TemplateConfig();
        templateConfig.setXml(null);
        new MyAutoGenerator().setGlobalConfig(config).setDataSource(dataSourceConfig).setStrategy(strategyConfig)
                .setCfg(crateInjectionConfig()).setTemplate(templateConfig)
                .setPackageInfo(
                        new PackageConfig().setParent(packageName).setController("controller").setEntity("entity"))
                .execute();
    }

    /**
     * 获取应用配置
     *
     * @return 应用配置
     * @throws IOException
     */
    private static Properties getApplicationProperties() throws IOException {
        Properties properties = new Properties();
        properties.load(GeneratorCodeByTables.class.getClassLoader().getResourceAsStream("application.properties"));
        return properties;
    }

    /**
     * 生成自定义配置
     *
     * @return 自定义配置
     */
    private static InjectionConfig crateInjectionConfig() {

        InjectionConfig cfg = new InjectionConfig() {

            @Override
            public void initMap() {
                // ignore
            }
        };

        List<FileOutConfig> focList = new ArrayList<>();
        focList.add(new FileOutConfig("/templates/mapper.xml.vm") {

            @Override
            public String outputFile(TableInfo tableInfo) {
                String mapperBasePath = "/";
                try {
                    mapperBasePath = new File("src/main/resources/mapper").getCanonicalPath();
                } catch (IOException e) {
                    // ignore
                }
                return mapperBasePath + "/" + tableInfo.getEntityName() + "Mapper.xml";
            }
        });

        cfg.setFileOutConfigList(focList);
        return cfg;
    }

    public static class MyAutoGenerator extends AutoGenerator {

        @Override
        protected ConfigBuilder pretreatmentConfigBuilder(ConfigBuilder config) {
            ConfigBuilder myConfig = super.pretreatmentConfigBuilder(config);

            myConfig.getTableInfoList().stream()
                    .forEach(tableInfo -> tableInfo.setImportPackages(Serializable.class.getCanonicalName()));

            return myConfig;
        }
    }
}
