package com.simuwang.daq.components.report.parser;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ReflectUtil;
import cn.hutool.core.util.StrUtil;
import com.simuwang.base.mapper.EmailFieldMappingMapper;
import com.simuwang.base.pojo.dos.EmailFieldMappingDO;
import com.simuwang.base.pojo.dto.report.ReportData;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.regex.Pattern;

/**
 * @author wangzaijun
 * @date 2024/9/30 18:13
 * @description 非python接口的报告解析抽象（主要是支持pdf、word和excel等格式）
 */
public abstract class AbstractReportParser<T extends ReportData> implements ReportParser<T> {
    protected final Logger logger = LoggerFactory.getLogger(this.getClass());

    private final EmailFieldMappingMapper fieldMappingMapper;
    /**
     * 字段匹配规则
     */
    protected Map<String, String> fieldMapper;

    public AbstractReportParser(EmailFieldMappingMapper fieldMappingMapper) {
        this.fieldMappingMapper = fieldMappingMapper;
        this.fieldMapper = MapUtil.newHashMap(128);
    }

    /**
     * 初始化数据的方法
     */
    protected void init() {
        List<EmailFieldMappingDO> emailFieldMapping = this.fieldMappingMapper.getEmailFieldMapping(3);
        if (CollUtil.isEmpty(emailFieldMapping)) {
            this.logger.error("未设置报告解析规则！");
            return;
        }
        for (EmailFieldMappingDO mapping : emailFieldMapping) {
            String code = mapping.getCode();
            List<String> names = StrUtil.split(mapping.getName(), ",");
            for (String name : names) {
                this.fieldMapper.putIfAbsent(name, code);
            }
        }
    }

    /**
     * 数据清洗，默认啥也不做
     *
     * @param reportData 结果数据
     */
    protected abstract void cleaningReportData(T reportData);

    /**
     * 对象字段设置
     *
     * @param extInfoMap 名称与值的对应关系
     * @param info       待设置的对象
     */
    protected void buildInfo(Map<String, Object> extInfoMap, Object info) {
        if (MapUtil.isEmpty(extInfoMap)) {
            return;
        }
        for (Map.Entry<String, Object> entry : extInfoMap.entrySet()) {
            String k = this.cleaningValue(entry.getKey());
            String fieldValue = this.cleaningValue(entry.getValue());
            String fieldName = this.fieldMapper.get(k);
            if (StrUtil.isBlank(fieldName)) {
                continue;
            }
            try {
                ReflectUtil.setFieldValue(info, fieldName, fieldValue);
            } catch (Exception e) {
                this.logger.warn("{} 字段值设置错误：{}", fieldName, e.getMessage());
            }
        }
    }

    protected String cleaningValue(Object value) {
        return this.cleaningValue(value, true);
    }

    /**
     * 数据简单清洗，并全部转为字符串类型
     *
     * @param value              待清洗的数据
     * @param replaceParentheses 是否替换圆括号
     * @return /
     */
    protected String cleaningValue(Object value, boolean replaceParentheses) {
        String fieldValue = StrUtil.toStringOrNull(value);
        if (!StrUtil.isNullOrUndefined(fieldValue)) {
            // 特殊字符替换，空格替换为空字符
            fieldValue = fieldValue
                    .replace("\r", StrUtil.EMPTY)
                    .replace("；", ";")
                    .replaceAll(" ", StrUtil.EMPTY);
            if (replaceParentheses) {
                // 正则表达式匹配中文括号及其内容，并替换为空字符串
                fieldValue = Pattern.compile("[（|(][^）]*[）|)]").matcher(fieldValue).replaceAll(StrUtil.EMPTY);
            }
        }
        // 如果仅有 “-” 该字段值为null
        if (Objects.equals("-", fieldValue)) {
            fieldValue = null;
        }
        return StrUtil.isBlank(fieldValue) ? null : fieldValue;
    }
}
