package com.wmyun.module.infra.service.file;

import com.wmyun.farmwork.word.deprecated.core.TemplateReplaceExecutor;
import com.wmyun.farmwork.word.deprecated.core.TemplateTagsGenerate;
import com.wmyun.farmwork.word.deprecated.core.model.exec.TemplateExecDataModel;
import com.wmyun.farmwork.word.deprecated.core.model.gen.TagsGenDataModel;
import com.wmyun.module.infra.dal.dataobject.file.FileDO;
import com.wmyun.module.infra.framework.file.core.client.FileClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;

/**
 * @Description: TODO
 * @Date: 2025/3/1 10:33
 * @Created: by ZZSLL
 */

@Service
public class WordTemplateTagServiceImpl implements WordTemplateTagService {

    @Autowired
    private FilePreviewService previewService;

    @Autowired
    private FileConfigService fileConfigService;

    @Autowired
    private FileService fileService;

    @Override
    public List<TagsGenDataModel> queryAllTag(String fileId) throws Exception {

        return TemplateTagsGenerate.execAllTags(saveFileToLocalTmp(fileId));
    }

    private String saveFileToLocalTmp(String fileId) throws Exception {
        FileDO file = getFileInfo(fileId);
        FileClient client = fileConfigService.getFileClient(file.getConfigId());
        byte[] content = client.getContent(file.getPath());

        String name = file.getName();
        Path tempDir = Paths.get(System.getProperty("java.io.tmpdir"));
        Path targetPath = tempDir.resolve(name);
        Files.write(targetPath, content);

        return targetPath.toString();
    }

    private FileDO getFileInfo(String fileId) {
        return previewService.queryFileInfoByFileId(fileId);
    }

    @Override
    public Long generateNew(String fileId, TemplateExecDataModel data) throws Exception {
        String inputPath = saveFileToLocalTmp(fileId);
        String outputPath = TemplateReplaceExecutor.doReplace(inputPath, data);
        FileDO fileInfo = getFileInfo(fileId);
        File file = new File(outputPath);
        byte[] content = Files.readAllBytes(file.toPath());
        String url = fileService.createFile(fileInfo.getName(), outputPath, content);
        return 0L;
    }
}
