package com.yaoyicloud.render.platform;

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.CommonDataCache;
import com.yaoyicloud.config.FilerepoProperties;
import com.yaoyicloud.factory.FXYAbstractRender;
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 org.apache.commons.collections4.MapUtils;

/**
 * AttachmentSection渲染器
 *
 */
@Slf4j
public final class AttachmentSectionRender extends FXYAbstractRender {
    private final FilerepoProperties filerepoProperties;
    private final CommonDataCache commonDataCache;

    public AttachmentSectionRender(String cwd, FilerepoProperties filerepoProperties, CommonDataCache commonDataCache) {
        super(cwd);
        this.filerepoProperties = filerepoProperties;
        this.commonDataCache = commonDataCache;
    }

    @Override
    protected Map<String, Object> renderDocx(String info, String relationId, Integer counter) throws IOException {
        log.info("开始渲染附件模块，relationId: {}", relationId);

        FxyProtos.AttachmentSection.Builder attachmentSection = FxyProtos.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);
        }
        Map<String, Object> commonDataCacheData = commonDataCache.getData(relationId);
        if (MapUtils.isNotEmpty(commonDataCacheData)) {
            data.putAll(commonDataCacheData);
        }
        data.put("levelInteger", counter);
        fillDefaultValues(data);
        return data;
    }

    @Override
    protected ConfigureBuilder builder(String relationId) {
        // 配置POI-TL渲染器
        ConfigureBuilder builder = Configure.builder();
        builder.addPlugin('^', this.pictureRenderPolicy());
        builder.addPlugin('`', this.hyperlinkRenderPolicy());
        return builder;
    }

    @Override
    protected String getBasicPath() throws IOException {
        return filerepoProperties.getBasePath();
    }

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

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

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

}
