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

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.FilerepoProperties;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.MapUtils;

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

    public TaxRender(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 riskModuleBuilder = FxyProtos.RiskModule.newBuilder();
        JsonFormat.parser().merge(info, riskModuleBuilder);
        FxyProtos.RiskModule defaultInstance = FxyProtos.RiskModule.getDefaultInstance();
        FxyProtos.RiskModule mergedProto = defaultInstance.toBuilder()
            .mergeFrom(riskModuleBuilder.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);

        Map<String, Object> commonDataCacheData = commonDataCache.getData(relationId);
        if (MapUtils.isNotEmpty(commonDataCacheData)) {
            data.putAll(commonDataCacheData);
        }

        fillBasicDefaultValues(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, "tax_error_flag", false);
        List<Map<String, Object>> taxInfoChecks = (List<Map<String, Object>>) data.get("taxInfoChecks");
        if (CollectionUtils.isEmpty(taxInfoChecks)) {
            index++;
        } else {
            for (Map<String, Object> basicInfoCheck : taxInfoChecks) {
                String category = (String) basicInfoCheck.get("category");
                if (category == null) {
                    continue;
                }
                switch (category) {
                    case "tax_error":
                        index++;
                        otherMap.put("taxError", index.toString());
                        commonDataCache.insertData(relationId, "tax_error_flag", true);
                        break;
                    default:
                        break;
                }
            }
            index++;
        }
        otherMap.put("moduleTail", index.toString());
        data.put("taxMap", otherMap);
    }

    @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("taxPenalties",
            this.addDefaultRowForEmptyTable((Boolean) commonDataCacheData.get("tax_error_flag")));
        builder.bind("taxInfoChecks", indicatorsRenderPolicy);
        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 updateSource = data.get("updateSource");
        if (updateSource.equals("-")) {
            data.put("updateSource", "");
        }
        Object riskModuleCheckResult = data.get("riskModuleCheckResult");
        if (Objects.equals(riskModuleCheckResult, "-")) {
            data.put("riskModuleCheckResult", "0");
        }
        processJsonData(data, "taxPenalties");
    }
}
