package com.yaoyicloud.render;

import java.io.IOException;
import java.nio.file.Paths;
import java.util.Map;
import java.util.UUID;

import com.deepoove.poi.config.Configure;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.ser.std.StdSerializer;
import com.yaoyicloud.message.FxyProtos.ServiceProviderInfo;

import cn.hutool.core.util.StrUtil;

/**
 * ServiceProviderInfo渲染器
 *
 */
public final class ServiceProviderInfoRender extends AbstractRender {

    public ServiceProviderInfoRender(String cwd) {
        super(cwd);
    }

    /**
     * Docx 渲染
     *
     * @param info 数据
     * @param templateFileContent 模板内容
     * @return 本地文件目录
     * @throws IOException
     */
    public String renderDocx(ServiceProviderInfo info, Map<String, Object> addtionalMap, byte[] templateFileContent)
        throws IOException {
        ObjectMapper mapper = new ObjectMapper();
        SimpleModule module = new SimpleModule();
        module.addSerializer(new ServiceProviderInfoSerializer(ServiceProviderInfo.class));
        mapper.registerModule(module);

        String jsonStr = mapper.writeValueAsString(info);

        // 注： 报告模板的模板变量按照json序列化的结果命名
        // 注： 目前的实现假设：一个session对应一个cwd目录
        this.docxResultPath =
            this.renderDocx(jsonStr, addtionalMap, templateFileContent, Configure.builder(),
                Paths.get(cwd, UUID.randomUUID().toString() + ".docx").toString());
        return this.docxResultPath;
    }

    /*
     * 通过序列化和反序列化
     * 1. 进行默认显示规则的数据转换
     * 2. 避免POI-TL处理模板面对复杂数据类型
     */
    public class ServiceProviderInfoSerializer extends StdSerializer<ServiceProviderInfo> {

        public ServiceProviderInfoSerializer() {
            this(null);
        }

        public ServiceProviderInfoSerializer(Class<ServiceProviderInfo> t) {
            super(t);
        }

        @Override
        public void serialize(ServiceProviderInfo value, JsonGenerator jgen, SerializerProvider provider)
            throws IOException, JsonProcessingException {

            jgen.writeStartObject();
            jgen.writeStringField("name", StrUtil.isBlank(value.getName()) ? "-" : value.getName());
            jgen.writeStringField("type", StrUtil.isBlank(value.getType()) ? "-" : value.getType());
            jgen.writeStringField("reportDate", value.getReportDate());
            jgen.writeEndObject();
        }
    }
}
