package com.xy;

import com.baomidou.mybatisplus.annotation.IdType;
import com.xy.utils.MybatisGenerator2;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.io.File;

/**
 * 自动生成代码
 */
@Slf4j
@Component
public class GenCode {
    /**
     * 服务名，不含xy-
     */
    public static final String SERVICE_NAME = "device";
    /**
     * 作者
     */
    public static final String AUTHOR = "谭斌";


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

    public static void gen2() {
        MybatisGenerator2.Generator.builder()
                .author(AUTHOR)
                .commPath(getCommPath(SERVICE_NAME))
                .dtoModule(SERVICE_NAME + "-api")
                .dtoPackage("com.xy")
                .serviceModule(SERVICE_NAME + "-api")
                .servicePackage("com.xy")
                .implModule(SERVICE_NAME + "-api-service")
                .implPackage("com.xy")
                .mapperModule(SERVICE_NAME + "-api-service")
                .mapperPackage("com.xy")
                .feignModule(SERVICE_NAME + "-api-cloud")
                .feignPackage("com.xy")
                .entityModule(SERVICE_NAME + "-api-service")
                .entityPackage("com.xy")
                .idType(IdType.ASSIGN_ID)
                .autoFill(true)
                .deleteFieldName("deleted")
                .build().create();
    }

    /**
     * 获取项目的根路径
     *
     * @return
     */
    private static String getCommPath(String serviceName) {
        // "xy-merc\merc-start\target\classes"
        String strReplace = String.format("xy-%s\\%s-start\\target\\classes", serviceName, serviceName);
        // 获取当前类的路径
        String className = GenCode.class.getName().replace('.', '/') + ".class";
        String classPath = GenCode.class.getClassLoader().getResource(className).getPath();
        // 获取当前类的目录
        File classFile = new File(classPath);
        String classDir = classFile.getParentFile().getParentFile().getAbsolutePath();
        // 构建 commPath
        String commPath = classDir.substring(0, classDir.lastIndexOf(File.separator));
        commPath = commPath.replace(strReplace, "") + "xy-" + serviceName;
        return commPath;
    }
}

