package com.wmyun.farmwork.word.deprecated.core;

import com.deepoove.poi.XWPFTemplate;
import com.deepoove.poi.config.Configure;
import com.deepoove.poi.data.Pictures;
import com.deepoove.poi.data.Texts;
import com.wmyun.farmwork.word.deprecated.config.DefaultConfig;
import com.wmyun.farmwork.word.deprecated.core.model.exec.TemplateExecDataModel;
import com.wmyun.farmwork.word.deprecated.core.model.type.TypeImage;
import com.wmyun.farmwork.word.deprecated.core.model.type.TypeText;
import jakarta.validation.constraints.NotNull;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description: TODO
 * @Date: 2025/3/1 11:52
 * @Created: by ZZSLL
 */

@Component
@Deprecated
public class TemplateReplaceExecutor {
    public static String doReplace(@NotNull String absolutePath, TemplateExecDataModel data) {
        return doReplace(absolutePath, data, DefaultConfig.def());
    }

    private static String doReplace(@NotNull String absolutePath, TemplateExecDataModel data, Configure def) {
        File wordFile = new File(absolutePath);
        Map<String, Object> dataMap = new HashMap<>();
        for (TypeText text : data.getText()) {
            dataMap.put(text.getName(), Texts
                    .of(text.getValue()).create());
        }
        for (TypeImage image : data.getImage()) {
            dataMap.put(image.getName(), Pictures
                    .of(image.getValue())
                    .size(image.getWidth(), image.getHeight())
                    .create());
        }
        XWPFTemplate word = XWPFTemplate.compile(absolutePath, def).render(dataMap);
        String name = wordFile.getName();
        String tmpDir = System.getProperty("java.io.tmpdir");
        String output = tmpDir + File.separator + name;
        try {
            word.writeAndClose(new FileOutputStream(output));
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }

        return output;
    }
}
