package com.smppw.modaq.application.components.report.parser.ai;

import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.smppw.modaq.application.components.report.parser.ReportParserConstant;
import com.smppw.modaq.common.enums.ReportParseStatus;
import com.smppw.modaq.common.exception.ReportParseException;
import com.smppw.modaq.domain.dto.report.*;
import com.smppw.modaq.domain.mapper.EmailFieldMappingMapper;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;

@Component(ReportParserConstant.PARSER_AI_LETTER)
public class AILetterReportParser extends AbstractAIReportParser<LetterReportData> {
    public AILetterReportParser(EmailFieldMappingMapper fieldMappingMapper) {
        super(fieldMappingMapper);
    }

    @Override
    protected boolean isSupportAIParse() {
        return true;
    }

    @Override
    @SuppressWarnings("unchecked")
    protected void handleAiResult(String result) throws ReportParseException {
        try {
            JSONObject jsonObject = JSONUtil.parseObj(result);
            this.allInfoMap.putAll(flattenMap(jsonObject, ListUtil.list(false)));
            if (this.allInfoMap.containsKey("交易确认明细")) {
                Object temp = this.allInfoMap.remove("交易确认明细");
                if (temp instanceof Map<?, ?> map) {
                    this.allInfoMap.putAll((Map<String, Object>) map);
                } else if (temp instanceof List<?> list && !list.isEmpty()) {
                    this.allInfoMap.putAll((Map<String, Object>) list.get(0));
                }
            }
        } catch (Exception e) {
            throw new ReportParseException(ReportParseStatus.PARSE_HANDLE_FAIL);
        }
    }

    @Override
    protected LetterReportData parseExtInfoAndSetData(ReportBaseInfoDTO reportInfo, ReportFundInfoDTO fundInfo) throws ReportParseException {
        Integer fileId = reportInfo.getFileId();
        if (this.logger.isInfoEnabled()) {
            this.logger.info("文件{} 解析内容是：{}", fileId, this.allInfoMap);
        }
        // 投资者信息
        ReportInvestorInfoDTO investorInfo = this.buildDto(fileId, ReportInvestorInfoDTO.class, this.allInfoMap);
        // 交易流水
        ReportFundTransactionDTO fundTransaction = this.buildDto(fileId, ReportFundTransactionDTO.class, this.allInfoMap);
        // 构建结果数据
        LetterReportData reportData = new LetterReportData(reportInfo, fundInfo);
        reportData.setFundTransaction(fundTransaction);
        reportData.setInvestorInfo(investorInfo);
        return reportData;
    }

    @Override
    protected ReportFundInfoDTO buildFundInfo(ReportParserParams params) {
        return this.buildDto(params.getFileId(), ReportFundInfoDTO.class, this.allInfoMap);
    }

    @SuppressWarnings("unchecked")
    private static Map<String, Object> flattenMap(Map<String, Object> data, List<String> keys) {
        Map<String, Object> result = MapUtil.newHashMap(16);
        for (Map.Entry<String, Object> entry : data.entrySet()) {
            List<String> currKeys = ListUtil.toList(keys);
            currKeys.add(entry.getKey());
            if (entry.getValue() instanceof Map<?, ?>) {
                result.putAll(flattenMap((Map<String, Object>) entry.getValue(), currKeys));
            } else {
                result.put(entry.getKey(), entry.getValue());
            }
        }
        return result;
    }
}
