package com.ag.secp.platform.common;

import com.ag.web.mobile.TestProperties;
import com.baomidou.mybatisplus.annotation.IdType;
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.OracleTypeConvert;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.DateType;
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 com.wb.common.Base;
import com.wb.interact.FileGenProcess;
import com.wb.util.FileUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 代码生成工具
 */
public class CodeGeneratorUtil {


    public static synchronized void addFrame(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String name = request.getParameter("name");
        String title = request.getParameter("title");
        String iconCls = request.getParameter("iconCls");
        File path = new File(request.getParameter("path"));
        String frameType = request.getParameter("frameType");
        String tablename = request.getParameter("tableName");

        String packgename = "com.ag.devbusiness";
        String entityname = underline2Camel(tablename, false);
        FileGenProcess fileGenProcess = new FileGenProcess();
        request.setAttribute("controllername", entityname);
        request.setAttribute("packagename", packgename);
        request.setAttribute("entityname", packgename + "." + name + ".entity." + entityname);
        request.setAttribute("servicebean", entityname + "ServiceImpl");
        fileGenProcess.addFrame(request, response);
        if (request.getParameter("genback") != null && request.getParameter("genback").equals("true")) {
            genCode(name, tablename, packgename);
        }
    }


    /**
     * <p>
     * 读取控制台内容
     * </p>
     * <p>
     * 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 + "！");
     * }
     */
    public static void genCode(String modulename, String talename, String packgename) throws Exception {
        // 代码生成器
        AutoGenerator mpg = new AutoGenerator();

        // 全局配置
        GlobalConfig gc = new GlobalConfig();
        String projectPath = System.getProperty("user.dir");
        // gc.setOutputDir(projectPath + "/Neptune/src/main/java");

        Properties ps = new Properties();
        ps.load(CodeGeneratorUtil.class.getClassLoader().getResourceAsStream("a.properties"));
        String url = ps.getProperty("workurl");
        gc.setOutputDir(url + "/java");

        gc.setAuthor("running-shao");
        gc.setIdType(IdType.UUID);
        gc.setOpen(false);
        gc.setDateType(DateType.ONLY_DATE);
        // gc.setSwagger2(true); 实体属性 Swagger2 注解
        mpg.setGlobalConfig(gc);

        // 数据源配置
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setUrl("jdbc:oracle:thin:@192.168.1.188:1521:agsoft");
        dsc.setDriverName("oracle.jdbc.driver.OracleDriver");
        dsc.setUsername("ag_dev");
        dsc.setPassword("ok");
        dsc.setTypeConvert(new OraclePlugintypeConert());
        mpg.setDataSource(dsc);

        // 包配置
        PackageConfig pc = new PackageConfig();
        pc.setModuleName(modulename);
        pc.setParent(packgename);

        mpg.setPackageInfo(pc);

        // 自定义配置
        InjectionConfig cfg = new InjectionConfig() {
            @Override
            public void initMap() {
                // to do nothing
            }
        };

        // 如果模板引擎是 freemarker
        String templatePath = "/templates/mapper.xml.ftl";
        // 如果模板引擎是 velocity
        // String templatePath = "/templates/mapper.xml.vm";

        // 自定义输出配置
        List<FileOutConfig> focList = new ArrayList<>();
        // 自定义配置会被优先输出
        focList.add(new FileOutConfig(templatePath) {
            @Override
            public String outputFile(TableInfo tableInfo) {
                // 自定义输出文件名 ， 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化！！
                return url + "/resources/mapper"
                        + "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
            }
        });
        /*
        cfg.setFileCreate(new IFileCreate() {
            @Override
            public boolean isCreate(ConfigBuilder configBuilder, FileType fileType, String filePath) {
                // 判断自定义文件夹是否需要创建
                checkDir("调用默认方法创建的目录");
                return false;
            }
        });
        */
        cfg.setFileOutConfigList(focList);
        mpg.setCfg(cfg);

        // 配置模板
        TemplateConfig templateConfig = new TemplateConfig();

        // 配置自定义输出模板
        //指定自定义模板路径，注意不要带上.ftl/.vm, 会根据使用的模板引擎自动识别
        // templateConfig.setEntity("templates/entity2.java");
     //templateConfig.setService();
       // templateConfig.setController("/template/service.java");
        templateConfig.setController("/template/service.java");
         templateConfig.setService(null);
        templateConfig.setServiceImpl(null);


        templateConfig.setXml(null);
        mpg.setTemplate(templateConfig);

        // 策略配置
        StrategyConfig strategy = new StrategyConfig();

        strategy.setNaming(NamingStrategy.underline_to_camel);
        strategy.setColumnNaming(NamingStrategy.underline_to_camel);
        //  strategy.setSuperEntityClass("com.baomidou.ant.common.BaseEntity");
        strategy.setEntityLombokModel(true);
        strategy.setRestControllerStyle(true);
        // strategy.setSuperControllerClass("com.baomidou.ant.common.BaseController");
        strategy.setInclude(talename.split(","));
        strategy.setSuperEntityColumns("id");
        strategy.setControllerMappingHyphenStyle(true);
        strategy.setTablePrefix(pc.getModuleName() + "_");
        mpg.setStrategy(strategy);
        mpg.setTemplateEngine(new FreemarkerTemplateEngine());
        mpg.execute();
    }


    public static String underline2Camel(String line, boolean... smallCamel) {
        if (line == null || "".equals(line)) {
            return "";
        }
        StringBuffer sb = new StringBuffer();
        Pattern pattern = Pattern.compile("([A-Za-z\\d]+)(_)?");
        Matcher matcher = pattern.matcher(line);
        //匹配正则表达式
        while (matcher.find()) {
            String word = matcher.group();
            //当是true 或则是空的情况
            if ((smallCamel.length == 0 || smallCamel[0]) && matcher.start() == 0) {
                sb.append(Character.toLowerCase(word.charAt(0)));
            } else {
                sb.append(Character.toUpperCase(word.charAt(0)));
            }

            int index = word.lastIndexOf('_');
            if (index > 0) {
                sb.append(word.substring(1, index).toLowerCase());
            } else {
                sb.append(word.substring(1).toLowerCase());
            }
        }
        return sb.toString();
    }
/*

    public static  String underlineToCamel(String name) {
        if (StringUtils.isEmpty(name)) {
            return "";
        } else {
            String tempName = name;
            if (StringUtils.isCapitalMode(name) || StringUtils.isMixedMode(name)) {
                tempName = name.toLowerCase();
            }

            StringBuilder result = new StringBuilder();
            String[] camels = tempName.split("_");
            Arrays.stream(camels).filter((camel) -> {
                return !StringUtils.isEmpty(camel);
            }).forEach((camel) -> {
                if (result.length() == 0) {
                    result.append(camel);
                } else {
                    result.append(capitalFirst(camel));
                }

            });
            return result.toString();
        }
    }


    public static String capitalFirst(String name) {
        return StringUtils.isNotEmpty(name) ? name.substring(0, 1).toUpperCase() + name.substring(1) : "";
    }
*/


}