package com.njzscloud.common.gen.support;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.njzscloud.common.core.ex.Exceptions;
import com.njzscloud.common.core.jackson.Jackson;
import com.njzscloud.common.core.tuple.Tuple3;
import com.njzscloud.common.gen.TplEntity;
import com.njzscloud.common.gen.TplService;
import lombok.extern.slf4j.Slf4j;

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

@Slf4j
public class Generator {
    private static final DbMetaData dbMetaData = SpringUtil.getBean(DbMetaData.class);
    private static final TplService tplService = SpringUtil.getBean(TplService.class);

    private static Tuple3<String, String, String> generate0(String tplName, String tableName, Map<String, Object> data) {

        Assert.notBlank(tableName, () -> Exceptions.clierr("未指定表名称"));
        data.put("tableName", tableName);
        List<Map<String, Object>> table = dbMetaData.getTableMetaData(tableName);
        TplEntity tplEntity = tplService.getOne(Wrappers.<TplEntity>lambdaQuery()
            .eq(TplEntity::getTplName, tplName));

        Tpl tpl = tplEntity.getTpl();
        Map<String, Object> modelData = tplEntity.getModelData();
        HashMap<String, Object> map = new HashMap<>(modelData);
        map.put("table", CollUtil.isNotEmpty(table) ? table.getFirst() : MapUtil.empty());
        map.putAll(data);
        log.info("数据：{}", Jackson.toJsonStr(map));
        TemplateEngine templateEngine = TemplateEngine.getEngine(tplName, tpl);
        String content = templateEngine.renderContent(map);
        String dir = templateEngine.renderDir(map);
        String filename = templateEngine.renderFilename(map);
        return Tuple3.of(dir, StrUtil.isBlank(filename) ? tplName + ".txt" : filename, content);
    }

    /**
     *
     * @param tplName   模板名称
     * @param tableName 表名称
     * @param data      数据
     * @return 0-->文件夹、1-->文件名、2-->内容
     */
    public static Tuple3<String, String, String> generate(String tplName, String tableName, Map<String, Object> data) {
        return generate0(tplName, tableName, data == null ? new HashMap<>() : data);
    }
}
