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

    public OperationalRender(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.FinancialInfo.Builder financialInfoBuilder = FxyProtos.FinancialInfo.newBuilder();
        JsonFormat.parser().merge(info, financialInfoBuilder);

        FxyProtos.FinancialInfo defaultInstance = FxyProtos.FinancialInfo.getDefaultInstance();
        FxyProtos.FinancialInfo mergedProto = defaultInstance.toBuilder()
            .mergeFrom(financialInfoBuilder.build())
            .build();
        if (!mergedProto.hasFinancialSummary()) {
            mergedProto = mergedProto.toBuilder()
                    .setFinancialSummary(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);
        // Map<String, Object> financialSummary = (Map<String, Object>) data.get("financialSummary");
        // data.put("fiancescore", financialSummary.get("score"));
        fillCommonDataCacheData(data, relationId);
        return data;
    }

    @Override
    protected ConfigureBuilder builder(String relationId) {
        ConfigureBuilder builder = Configure.builder();
        builder.useSpringEL();

        builder.bind("indicators", new LoopRowIncludeStatisticsTableRenderPolicy("values"));
        builder.bind("financialDataSeq", new LoopColumnStaticTableRenderPolicy("[", "]", false, true, 2));
        builder.bind("financialCheckDetails", new LoopRowCutAndMergeFirstColTableRenderPolicy());
        builder.bind("businessRiskChecks", this.indicatorsRenderPolicyToProtobuf());
        return builder;
    }

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

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

    private void fillCommonDataCacheData(Map<String, Object> data, String relationId) {
        boolean financialFlag = false;
        Object financialInfo = data.get("financialInfo");

        if (financialInfo != null && "是".equals(financialInfo.toString())) {
            financialFlag = true;
        }
        data.put("financialInfo_flag", financialFlag);

        Integer index = 1;
        Map<String, Object> operationalMap = new HashMap<>();
        if (financialFlag) {
            index++;
            operationalMap.put("financialDataSeq", index.toString());
            index++;
            operationalMap.put("indicators", index.toString());
            index++;
            operationalMap.put("financialCheckDetails", index.toString());
        }
        index++;
        operationalMap.put("moduleTail", index.toString());

        data.put("operationalMap", operationalMap);
    }

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

        Map<String, Object> financialSummary = (Map<String, Object>) data.get("financialSummary");
        financialSummary.replaceAll((k, v) -> v.equals("") ? "-" : v);
        data.put("certReceived_source", "(自主申报)");
        data.put("bankLicense_source", "(自主申报)");
        data.put("annualInspectionResult_source", "(自主申报)");
        Object certReceived = data.get("certReceived");
        if (Objects.equals(certReceived, "-")) {
            data.put("certReceived", "否");
            data.put("certReceived_source", "");
        }

        Object bankLicense = data.get("bankLicense");
        if (Objects.equals(bankLicense, "-")) {
            data.put("bankLicense", "否");
            data.put("bankLicense_source", "");
        }

        Object annualInspectionResult = data.get("annualInspectionResult");
        if (Objects.equals(annualInspectionResult, "-")) {
            data.put("annualInspectionResult", "否");
            data.put("annualInspectionResult_source", "");
        }
        Object financialDataSeqFlagSource = data.get("financialDataSeqFlagSource");
        if (Objects.equals(financialDataSeqFlagSource, "-")) {
            data.put("financialDataSeqFlagSource", "");
        }
        Object financialInfoCheckResult = data.get("financialInfoCheckResult");
        if (Objects.equals(financialInfoCheckResult, "-")) {
            data.put("financialInfoCheckResult", "0");
        }

        List<Map<String, Object>> financialDataSeq = (List<Map<String, Object>>) data.get("financialDataSeq");
        if (CollectionUtils.isNotEmpty(financialDataSeq)) {
            data.put("financialDataSeqFlag", "是");
        }
        data.put("financialDataSeqFlag", "否");
    }

}
