package org.nl.system.service.generator.impl;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.nl.system.service.generator.ICodeGenConfigService;
import org.nl.system.service.generator.dao.CodeGenConfig;
import org.nl.system.service.generator.dao.mapper.CodeGenConfigMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;

/**
 * <p>
 * 代码生成配置表 服务实现类
 * </p>
 *
 * @author lyd
 * @since 2023-05-03
 */
@Service
public class CodeGenConfigServiceImpl extends ServiceImpl<CodeGenConfigMapper, CodeGenConfig> implements ICodeGenConfigService {

    @Autowired
    private CodeGenConfigMapper codeGenConfigMapper;

    @Override
    public CodeGenConfig findByTableName(String tableName) {
        CodeGenConfig codeGenConfig = codeGenConfigMapper.selectOne(new LambdaQueryWrapper<CodeGenConfig>()
                .eq(CodeGenConfig::getTable_name, tableName));
        if (ObjectUtil.isEmpty(codeGenConfig)) {
            return new CodeGenConfig(tableName);
        }
        return codeGenConfig;
    }

    @Override
    public CodeGenConfig update(String tableName, CodeGenConfig genConfig) {
        // 如果 api 路径为空，则自动生成路径
        if(StrUtil.isEmpty(genConfig.getApi_path())){
            String separator = File.separator;
            String[] paths;
            String symbol = "\\";
            if (symbol.equals(separator)) {
                paths = genConfig.getPath().split("\\\\");
            } else {
                paths = genConfig.getPath().split(File.separator);
            }
            StringBuilder api = new StringBuilder();
            for (String path : paths) {
                api.append(path);
                api.append(separator);
                if ("src".equals(path)) {
                    api.append("api");
                    break;
                }
            }
            genConfig.setApi_path(api.toString());
        }
        if (ObjectUtil.isNotEmpty(genConfig.getConfig_id())) {
            codeGenConfigMapper.updateById(genConfig);
        } else {
            genConfig.setConfig_id(IdUtil.getSnowflake(1,1).nextIdStr());
            codeGenConfigMapper.insert(genConfig);
        }
        return genConfig;
    }
}
