package com.yaoyicloud.render;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yaoyicloud.config.FilerepoProperties;
import com.yaoyicloud.message.FxyProtos;
import lombok.extern.slf4j.Slf4j;

import com.deepoove.poi.config.Configure;
import com.deepoove.poi.config.ConfigureBuilder;
import com.google.protobuf.Descriptors;
import com.google.protobuf.util.JsonFormat;
import com.yaoyicloud.message.FxyProtos.AttachmentSection;

/**
 * AttachmentSection渲染器
 *
 */
@Slf4j
public final class AttachmentSectionRender extends AbstractRender {
    private final FilerepoProperties filerepoProperties;
    public AttachmentSectionRender(String cwd, FilerepoProperties filerepoProperties) {
        super(cwd);
        this.filerepoProperties = filerepoProperties;
    }
    @Override
    protected String getBasicPath() throws IOException {
        return filerepoProperties.getBasePath();
    }

    @Override
    protected String getReportImagePath() {
        return filerepoProperties.getReportImagePath();
    }

    /**
     * Docx 渲染
     *
     * @param info 数据
     * @param templateFileContent 模板内容
     * @return 本地文件目录
     * @throws IOException
     */

    public String renderDocx(String info, Map<String, Object> addtionalMap, byte[] templateFileContent, String relationId) throws IOException {
        log.info("开始渲染附件模块，relationId: {}", relationId);

        // 配置POI-TL渲染器
        ConfigureBuilder builder = Configure.builder();
        builder.addPlugin('^',  this.pictureRenderPolicy());
        builder.addPlugin('`',  this.hyperlinkRenderPolicy());

        AttachmentSection.Builder attachmentSection = AttachmentSection.newBuilder();
        JsonFormat.parser().merge(info, attachmentSection);

        FxyProtos.AttachmentSection defaultInstance = FxyProtos.AttachmentSection.getDefaultInstance();
        FxyProtos.AttachmentSection mergedProto = defaultInstance.toBuilder()
                .mergeFrom(attachmentSection.build())
                .build();

        Map<String, Object> newAddtionMap = new HashMap<>();
        Descriptors.Descriptor descriptor = mergedProto.getDescriptorForType();
        for (Descriptors.FieldDescriptor field : descriptor.getFields()) {
            if (field.isRepeated()) {
                List<?> li = (List<?>) mergedProto.getField(field);
                if (li.size() == 0) {
                    newAddtionMap.put(field.getName() + "AltText", "未上传");
                }
            }
        }

        String completeJson = JsonFormat.printer()
                .includingDefaultValueFields()
                .print(mergedProto);
        ObjectMapper objectMapper = new ObjectMapper();
        Map<String, Object> data = objectMapper.readValue(completeJson, new TypeReference<Map<String, Object>>() {});
        if (newAddtionMap != null) {
            data.putAll(newAddtionMap);
        }

        fillDefaultValues(data);
        try {
            // 渲染文档
            String resultPath = this.renderDocx(data, templateFileContent, builder, relationId);
            log.info("渲染附件模块成功，文件路径: {}", resultPath);
            return resultPath;
        } catch (Exception e) {
            log.error("渲染附件模块失败，relationId: {}", relationId, e);
            throw new IOException("文档渲染失败", e);
        }
    }


    /**
     * 填充默认值，确保所有必要字段都存在
     */
    private void fillDefaultValues(Map<String, Object> data) {

        ArrayList<String> fillDeclLinks = (ArrayList) data.get("fillDeclLinks");
        if (fillDeclLinks != null) {
            data.put("fillDeclLinksExits", true);

        }

    }


}
