package com.czg;

import cn.hutool.crypto.SecureUtil;
import com.czg.market.entity.MkLimitTimeDiscount;
import com.mybatisflex.codegen.Generator;
import com.mybatisflex.codegen.config.*;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.core.service.IService;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import com.zaxxer.hikari.HikariDataSource;

import java.util.HashMap;
import java.util.Map;

/**
 * @author ww
 */
public class CodeGen {
    //    private final static String BASE_URL = "rm-bp1kn7h89nz62cno1ro.mysql.rds.aliyuncs.com";
    private final static String BASE_URL = "192.168.1.43";
    private final static String PORT = "3306";
    private final static String USERNAME = "root";
    private final static String PASSWORD = "Chaozg123.";
    private final static String DATABASE = "czg_cashier";
    static String currentWorkingDirectory = System.getProperty("user.dir");
    static String basePackage = "com.czg.";

    public static void main(String[] args) {
        //or条件sql写法示例
//        orSqlTest();
        //修改密码
//        getPassword(1L, "czg2303");


//        String packageName = "system";
//        String packageName = "account";
//        String packageName = "product";
//        String packageName = "market";
        String packageName = "order";
        //  tableName   指定需要生成的表
        String tableName = "sys_print_data";
        String author = "ww";
        //是否生成DTO实体 默认生成
        boolean isGenerateDto = true;

        initTableEntity(packageName, tableName, author, isGenerateDto);
    }

    public static void initTableEntity(String packageName, String tableName, String author, boolean isGenerateDto) {
        //配置数据源
        HikariDataSource dataSource = new HikariDataSource();
        dataSource.setJdbcUrl("jdbc:mysql://" + BASE_URL + ":" + PORT + "/" + DATABASE);
        dataSource.setUsername(USERNAME);
        dataSource.setPassword(PASSWORD);

        String projectPath = currentWorkingDirectory + "/cash-service/" + packageName + "-service";

        // 生成 mapper 和 service实现
        GlobalConfig globalConfig = createGlobalConfigUseStyle(projectPath, packageName, "tb", tableName);
        globalConfig.setAuthor(author);
        Generator generator = new Generator(dataSource, globalConfig);
        generator.generate();

        // 生成 entity 和 service
        GlobalConfig serviceConfig = createServiceGlobalConfigUseStyle(currentWorkingDirectory + "/cash-common/cash-common-service",
                basePackage + packageName, "tb", tableName);
        Generator serviceGenerator = new Generator(dataSource, serviceConfig);
        serviceConfig.setAuthor(author);
        serviceGenerator.generate();

        //默认生成全参数DTO
        if (isGenerateDto) {
            GlobalConfig dtoConfig = createDtoGlobalConfig(currentWorkingDirectory + "/cash-common/cash-common-service",
                    basePackage + packageName, "tb", tableName);
            Generator dtoGenerator = new Generator(dataSource, dtoConfig);
            dtoConfig.setAuthor(author);
            dtoGenerator.generate();
        }
    }


    public static void orSqlTest() {
        QueryWrapper queryWrapper1 = new QueryWrapper();
        queryWrapper1.eq(MkLimitTimeDiscount::getId, 2)
                .or(MkLimitTimeDiscount::getShopId)
                .gt(25);
        System.out.println(queryWrapper1.toSQL());
        System.out.println();

        QueryWrapper queryWrapper3 = new QueryWrapper();
        queryWrapper3.eq(MkLimitTimeDiscount::getTitle, "王五")
                .or(wrapper -> {
                            wrapper.lt(MkLimitTimeDiscount::getShopId, 20)
                                    .gt(MkLimitTimeDiscount::getId, 100);
                        }
                );
        System.out.println(queryWrapper3.toSQL());
        System.out.println();

        QueryWrapper queryWrapper4 = new QueryWrapper();
        queryWrapper4.eq(MkLimitTimeDiscount::getTitle, "李四")
                .or("id BETWEEN ? AND ?", 20, 40);
        System.out.println(queryWrapper4.toSQL());
        System.out.println();

        Map<String, Object> conditions = new HashMap<>();
        conditions.put("age", 22);
        conditions.put("name", "赵六");
        conditions.put("name2", "赵六");

        QueryWrapper queryWrapper5 = new QueryWrapper();
        queryWrapper5.eq(MkLimitTimeDiscount::getId, 4)
                .or(conditions);
        System.out.println(queryWrapper5.toSQL());
        System.out.println();

        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq(MkLimitTimeDiscount::getShopId, 2)
                .eq(MkLimitTimeDiscount::getIsDel, 0)
                .orderBy(MkLimitTimeDiscount::getSort).desc()
                .orderBy(MkLimitTimeDiscount::getUpdateTime).desc();

        queryWrapper.and(q -> {
            q.eq(MkLimitTimeDiscount::getUseShopType, "all").or(q1 -> {
                q1.eq(MkLimitTimeDiscount::getUseShopType, "only").eq(MkLimitTimeDiscount::getShopId, 3);
            }).or(q2 -> {
                q2.eq(MkLimitTimeDiscount::getUseShopType, "custom").and(q3 -> {
                    q3.eq(MkLimitTimeDiscount::getShopId, 3).or("FIND_IN_SET( " + 3 + ", use_shops ) > 0");
                });
            });
        });

        System.out.println(queryWrapper.toSQL());
    }

    public static GlobalConfig createGlobalConfigUseStyle(String projectPath, String packageName, String tablePrefix, String... tableNames) {
        //创建配置内容
        GlobalConfig globalConfig = new GlobalConfig();

        //设置根包
        globalConfig.getPackageConfig()
                .setSourceDir(projectPath + "/src/main/java")

                .setEntityPackage(basePackage + packageName + ".entity")
                .setServicePackage(basePackage + packageName + ".service")

                .setServiceImplPackage(basePackage + "service." + packageName + ".service.impl")
                .setMapperPackage(basePackage + "service." + packageName + ".mapper")

                .setBasePackage(basePackage + "service." + packageName);

        globalConfig.getServiceConfig()
                .setClassSuffix("Service");

        globalConfig.getServiceImplConfig()
                .setClassSuffix("ServiceImpl")
                .setSuperClass(ServiceImpl.class);
        globalConfig.enableServiceImpl();
        globalConfig.setServiceImplTemplatePath("templates/serviceImpl.tpl");

        globalConfig.getMapperConfig()
                .setClassSuffix("Mapper");
        globalConfig.enableMapper();

        globalConfig.setMapperXmlPath(projectPath + "/src/main/resources/mapper");
        globalConfig.enableMapperXml();

        //设置表前缀和只生成哪些表，setGenerateTable 未配置时，生成所有表
        globalConfig.getStrategyConfig()
                .setTablePrefix(tablePrefix)
                .setGenerateTable(tableNames);

        //设置生成 mapper
        globalConfig.enableMapper();

        return globalConfig;
    }

    public static GlobalConfig createServiceGlobalConfigUseStyle(String projectPath, String packageName, String tablePrefix, String... tableNames) {
        //创建配置内容
        GlobalConfig globalConfig = new GlobalConfig();

        //设置根包
        globalConfig.getPackageConfig()
                .setSourceDir(projectPath + "/src/main/java")
                .setBasePackage(packageName);

        globalConfig.getServiceConfig()
                .setClassSuffix("Service")
                .setSuperClass(IService.class);
        globalConfig.enableService();

        //设置表前缀和只生成哪些表，setGenerateTable 未配置时，生成所有表
        globalConfig.getStrategyConfig()
                .setTablePrefix(tablePrefix)
                .setGenerateTable(tableNames);

        //设置生成 entity 并启用 Lombok
        globalConfig.enableEntity()
                .setWithLombok(true)
                .setJdkVersion(21);

        //可以单独配置某个列
        ColumnConfig createTime = new ColumnConfig();
        createTime.setColumnName("create_time");
        createTime.setOnInsertValue("now()");
        globalConfig.getStrategyConfig()
                .setColumnConfig(createTime);

        ColumnConfig updateTime = new ColumnConfig();
        updateTime.setColumnName("update_time");
        updateTime.setOnUpdateValue("now()");
        updateTime.setOnInsertValue("now()");
        globalConfig.getStrategyConfig()
                .setColumnConfig(updateTime);

//        ColumnConfig deleted = new ColumnConfig();
//        deleted.setColumnName("is_del");
//        deleted.setLogicDelete(true);
//        globalConfig.getStrategyConfig()
//                .setColumnConfig(deleted);

//        ColumnConfig version = new ColumnConfig();
//        version.setColumnName("version");
//        version.setVersion(true);
//        globalConfig.getStrategyConfig()
//                .setColumnConfig(version);

        return globalConfig;
    }

    public static GlobalConfig createDtoGlobalConfig(String projectPath, String packageName, String tablePrefix, String... tableNames) {
        //创建配置内容
        GlobalConfig globalConfig = new GlobalConfig();

        //设置根包
        globalConfig.getPackageConfig()
                .setEntityPackage(packageName + ".dto")
                .setSourceDir(projectPath + "/src/main/java")
                .setBasePackage(packageName);

        //设置表前缀和只生成哪些表，setGenerateTable 未配置时，生成所有表
        globalConfig.getStrategyConfig()
                .setTablePrefix(tablePrefix)
                .setGenerateTable(tableNames);
        globalConfig.setEntityTemplatePath("templates/entityDto.tpl");

        globalConfig.getEntityConfig()
                .setClassSuffix("DTO")
        ;

        //设置生成 entity 并启用 Lombok
        globalConfig.enableEntity()
                .setWithLombok(true)
                .setJdkVersion(21);

        return globalConfig;
    }

    public static void getPassword(Long sysUserId, String accountPwd) {
        System.out.println("将生成的密码 替换sys_user表中的密码即可");
        System.out.println(SecureUtil.md5(sysUserId + accountPwd));
        System.out.println("-------------------------------------");
    }

}
