package com.yaoyicloud.render.platform.update;

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

import com.deepoove.poi.config.Configure;
import com.deepoove.poi.config.ConfigureBuilder;
import com.deepoove.poi.policy.RenderPolicy;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.protobuf.util.JsonFormat;
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 org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;

@Slf4j
public final class OtherRender extends FXYAbstractRender {
    private final FilerepoProperties filerepoProperties;
    private final CommonDataCache commonDataCache;

    // 注入父类所需的 cwd 参数
    public OtherRender(String cwd, FilerepoProperties filerepoProperties, CommonDataCache commonDataCache) {
        super(cwd);
        this.filerepoProperties = filerepoProperties;
        this.commonDataCache = commonDataCache;
    }

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

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

    @Override
    protected Map<String, Object> renderDocx(String info, String relationId, Integer counter) throws IOException {
        log.info("开始渲染其他风险报告模块，relationId: {}", relationId);
        FxyProtos.RiskModule.Builder basicInfoBuilder = FxyProtos.RiskModule.newBuilder();
        JsonFormat.parser().merge(info, basicInfoBuilder);

        FxyProtos.RiskModule defaultInstance = FxyProtos.RiskModule.getDefaultInstance();
        FxyProtos.RiskModule mergedProto = defaultInstance.toBuilder()
            .mergeFrom(basicInfoBuilder.build())
            .build();
        if (!mergedProto.hasSummary()) {
            mergedProto = mergedProto.toBuilder()
                .setSummary(FxyProtos.CheckSummary.getDefaultInstance())
                .build();
        }
        String completeJson = JsonFormat.printer()
            .includingDefaultValueFields()
            .print(mergedProto);

        ObjectMapper objectMapper = new ObjectMapper();
        Map<String, Object> data = objectMapper.readValue(completeJson, new TypeReference<Map<String, Object>>() {});

        Map<String, Object> commonDataCacheData = commonDataCache.getData(relationId);
        if (MapUtils.isNotEmpty(commonDataCacheData)) {
            data.putAll(commonDataCacheData);
        }
        fillDefaultValues(data);
        data.put("levelInteger", counter);
        fillCommonDataCacheData(data, relationId);
        return data;
    }

    private void fillCommonDataCacheData(Map<String, Object> data, String relationId) {
        Integer index = 1;
        Map<String, Object> otherMap = new HashMap<>();
        commonDataCache.insertData(relationId, "integrity_guarantee_flag", false);
        data.put("relatedEntityImage_flag", false);

        data.put("files_flag", false);

        data.put("questionnaireItems_flag", false);

        data.put("questionnaireItemsTable_flag", false);

        data.put("questionnairs_flag", false);

        data.put("relatedEntityImagesAltText", "未上传");

        List<Map<String, Object>> otherRiskChecks = (List<Map<String, Object>>) data.get("otherRiskChecks");

        if (CollectionUtils.isEmpty(otherRiskChecks)) {
            index++;
        } else {
            for (Map<String, Object> basicInfoCheck : otherRiskChecks) {
                String category = (String) basicInfoCheck.get("category");
                if (category == null) {
                    continue;
                }
                switch (category) {
                    case "interest_conflict":
                        index++;
                        otherMap.put("relatedEntityImage", index.toString());
                        data.put("relatedEntityImage_flag", true);
                        data.put("relatedEntityImagesAltText", " ");
                        break;
                    case "integrity_guarantee":
                        index++;
                        data.put("questionnaireItems_flag", true);
                        List<Map<String, Object>> questionnaireItems =
                            (List<Map<String, Object>>) data.get("questionnaireItems");
                        if (CollectionUtils.isNotEmpty(questionnaireItems)) {
                            data.put("questionnaireItemsTable_flag", true);
                        }

                        Object o = data.get("questionnairs");
                        if (o != null) {
                            data.put("questionnairs_flag", true);
                            data.put("questionnairsAltText", " ");
                        } else {
                            data.put("questionnairsAltText", "未上传");
                        }

                        otherMap.put("questionnaireItems", index.toString());
                        break;
                    case "project_information":
                        index++;
                        otherMap.put("files", index.toString());
                        data.put("files_flag", true);
                        List<Map<String, Object>> files =
                            (List<Map<String, Object>>) data.get("files");
                        if (CollectionUtils.isEmpty(files)) {
                            data.put("filesAltText", "未上传");
                        } else {
                            data.put("filesAltText", "");
                        }

                        break;

                    default:
                        break;
                }
            }
            index++;
        }

        otherMap.put("moduleTail", index.toString());
        data.put("otherMap", otherMap);
    }

    @Override
    protected ConfigureBuilder builder(String relationId) {
        // 配置POI-TL渲染器
        ConfigureBuilder builder = Configure.builder();
        RenderPolicy indicatorsRenderPolicy = this.indicatorsRenderPolicyToProtobuf();
        builder.bind("questionnaireItems", indicatorsRenderPolicy);
        builder.bind("otherRiskChecks", indicatorsRenderPolicy);
        builder.addPlugin('^', this.pictureRenderPolicy());
        builder.useSpringEL();
        return builder;
    }

    /**
     * 填充默认值，确保所有必要字段都存在
     */
    private void fillDefaultValues(Map<String, Object> data) {
        Map<String, Object> summary = (Map<String, Object>) data.get("summary");
        summary.replaceAll((k, v) -> v.equals("") ? "-" : v);
        Object riskModuleCheckResult = data.get("riskModuleCheckResult");
        if (Objects.equals(riskModuleCheckResult, "-")) {
            data.put("riskModuleCheckResult", "0");
        }
        processJsonData(data, "questionnaireItems");
    }

}
