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 JudicialRender extends FXYAbstractRender {
    private final FilerepoProperties filerepoProperties;
    private final CommonDataCache commonDataCache;

    public JudicialRender(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.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>>() {});
        data.replaceAll((k, v) -> v.equals("") ? "-" : v);
        fillBasicDefaultValues(data);
        Map<String, Object> commonDataCacheData = commonDataCache.getData(relationId);
        if (MapUtils.isNotEmpty(commonDataCacheData)) {
            data.putAll(commonDataCacheData);
        }
        data.put("levelInteger", counter);
        fillCommonDataCacheData(data, relationId);
        return data;
    }

    private void fillCommonDataCacheData(Map<String, Object> data, String relationId) {
        Integer index = 1;
        Map<String, Object> judicialMap = new HashMap<>();

        commonDataCache.insertData(relationId, "dishonest_person_error_flag", false);
        commonDataCache.insertData(relationId, "serious_illegal_error_flag", false);
        List<Map<String, Object>> judicialRiskChecks = (List<Map<String, Object>>) data.get("judicialRiskChecks");
        if (CollectionUtils.isEmpty(judicialRiskChecks)) {
            index++;
        } else {
            for (Map<String, Object> basicInfoCheck : judicialRiskChecks) {
                String category = (String) basicInfoCheck.get("category");
                if (category == null) {
                    continue;
                }
                switch (category) {
                    case "dishonest_person_error":
                        index++;
                        judicialMap.put("dishonestPersons", index.toString());
                        commonDataCache.insertData(relationId, "dishonest_person_error_flag", true);
                        break;
                    case "serious_illegal_error":
                        index++;
                        judicialMap.put("severeViolations", index.toString());
                        commonDataCache.insertData(relationId, "serious_illegal_error_flag", true);
                        break;
                    default:
                        break;
                }
            }
            index++;
        }

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

    @Override
    protected ConfigureBuilder builder(String relationId) {
        // 配置POI-TL渲染器
        ConfigureBuilder builder = Configure.builder();
        RenderPolicy indicatorsRenderPolicy = this.indicatorsRenderPolicyToProtobuf();
        Map<String, Object> commonDataCacheData = commonDataCache.getData(relationId);
        builder.bind("dishonestPersons",
            this.addDefaultRowForEmptyTable((Boolean) commonDataCacheData.get("dishonest_person_error_flag")));
        builder.bind("judicialRiskChecks", indicatorsRenderPolicy);
        builder.bind("severeViolations",
            this.addDefaultRowForEmptyTable((Boolean) commonDataCacheData.get("serious_illegal_error_flag")));
        builder.useSpringEL();
        return builder;
    }

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

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

    /**
     * 填充默认值，确保所有必要字段都存在
     */
    private void fillBasicDefaultValues(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, "dishonestPersons");
        processJsonData(data, "severeViolations");
    }
}
