package com.njzscloud.common.gen.support;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.njzscloud.common.core.jackson.Jackson;
import com.njzscloud.common.core.tuple.Tuple3;
import com.njzscloud.common.gen.SysTplEntity;
import com.njzscloud.common.gen.SysTplService;
import lombok.extern.slf4j.Slf4j;

import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
public class Generator {
    private static Tuple3<String, String, String> generate0(String tplName, Map<String, Object> data) {
        DbMetaData dbMetaData = SpringUtil.getBean(DbMetaData.class);
        SysTplService sysTplService = SpringUtil.getBean(SysTplService.class);
        List<Map<String, Object>> table = dbMetaData.getMetaData(data.getOrDefault("tableName", "%").toString());
        SysTplEntity tplEntity = sysTplService.getOne(Wrappers.<SysTplEntity>lambdaQuery()
                .eq(SysTplEntity::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.get(0) : 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.create(dir, filename, content);
    }

    public static void generate(String tplName, Map<String, Object> data) {
        Tuple3<String, String, String> tuple3 = generate0(tplName, data == null ? MapUtil.empty() : data);
        String dir = tuple3.get_0();
        FileUtil.mkdir(dir);
        FileUtil.writeUtf8String(tuple3.get_2(), dir + "/" + tuple3.get_1());
    }

    public static void generate(String tplName, Map<String, Object> data, OutputStream out) {
        Tuple3<String, String, String> tuple3 = generate0(tplName, data == null ? MapUtil.empty() : data);
        log.info("结果：{}", tuple3.get_2());
        IoUtil.write(out, false, tuple3.get_2().getBytes(StandardCharsets.UTF_8));
    }
}
