package com.openhis.web.paymentmanage.appservice.impl;


import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.openhis.web.paymentmanage.util.ReverseMappingProperties;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Service;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;


@Service
@ConfigurationProperties(prefix = "threepart.mapping")
@Data
@Slf4j
public class ThreePartSimpleFieldMappingService {


    @Autowired
    private ReverseMappingProperties properties;

    private final ObjectMapper objectMapper = new ObjectMapper();

    /**
     * 执行反向映射：三方JSON -> 我方JSON
     */
    public String reverseMap(String businessType, String sourceJson) {
        try {
            // 1. 获取映射配置
            Map<String, String> mappingConfig = properties.getMappingConfig(businessType);
            if (mappingConfig.isEmpty()) {
                log.warn("未找到业务类型[{}]的映射配置", businessType);
                return sourceJson; // 返回原JSON
            }

            // 2. 解析源JSON
            Map<String, Object> sourceMap;
            sourceMap = objectMapper.readValue(sourceJson, new TypeReference<Map<String,Object>>(){});

            // 3. 执行反向映射
            Map<String, Object> resultMap = reverseMap(mappingConfig, sourceMap);

            // 4. 生成结果JSON
            return objectMapper.writeValueAsString(resultMap);

        } catch (Exception e) {
            log.error("反向映射失败，业务类型: {}, JSON: {}", businessType, sourceJson, e);
            throw new RuntimeException("反向映射失败", e);
        }
    }

    /**
     * 执行反向映射：Map版本
     */
    public Map<String, Object> reverseMap(String businessType, Map<String, Object> sourceMap) {
        Map<String, String> mappingConfig = properties.getMappingConfig(businessType);
        return reverseMap(mappingConfig, sourceMap);
    }

    /**
     * 核心映射逻辑
     */
    private Map<String, Object> reverseMap(Map<String, String> mappingConfig,
                                           Map<String, Object> sourceMap) {
        Map<String, Object> resultMap = new HashMap<>();

        for (Map.Entry<String, Object> entry : sourceMap.entrySet()) {
            String sourceField = entry.getKey();
            Object value = entry.getValue();

            // 查找映射关系
            String targetField = mappingConfig.get(sourceField);

            if (targetField != null) {
                // 执行映射
                resultMap.put(targetField, value);
            } else {
                // 未配置映射的字段，可以选择保留或忽略
                // resultMap.put(sourceField, value); // 取消注释则保留未映射字段
                log.debug("字段[{}]未配置映射，已忽略", sourceField);
            }
        }

        log.debug("反向映射完成: {} -> {}", sourceMap.keySet(), resultMap.keySet());
        return resultMap;
    }

    /**
     * 批量处理
     */
    public List<Map<String, Object>> reverseMapBatch(String businessType,
                                                     List<Map<String, Object>> sourceList) {
        return sourceList.stream()
                .map(source -> reverseMap(businessType, source))
                .collect(Collectors.toList());
    }

    /**
     * 检查字段是否已配置映射
     */
    public boolean isFieldMapped(String businessType, String fieldName) {
        Map<String, String> mappingConfig = properties.getMappingConfig(businessType);
        return mappingConfig.containsKey(fieldName);
    }

    /**
     * 获取所有已配置的映射字段
     */
    public Set<String> getMappedFields(String businessType) {
        Map<String, String> mappingConfig = properties.getMappingConfig(businessType);
        return mappingConfig.keySet();
    }
}
