package com.hotwj.platform.reportStatistics.service.impl;

import cn.hutool.core.util.StrUtil;
import com.hotwj.platform.reportStatistics.domain.vo.SysReportTemplateVo;
import com.hotwj.platform.reportStatistics.service.ISysReportTemplateService;
import org.apache.velocity.exception.ResourceNotFoundException;
import org.apache.velocity.runtime.resource.Resource;
import org.apache.velocity.runtime.resource.loader.ResourceLoader;
import org.apache.velocity.util.ExtProperties;
import org.dromara.common.core.utils.SpringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.Reader;
import java.io.StringReader;

/**
 * 动态 Velocity 模版加载器
 * <p>
 * 优先从数据库加载模版，用于支持在线编辑和实时预览。
 * </p>
 *
 * @author shihongwei
 */
public class DynamicVelocityTemplateLoader extends ResourceLoader {

    private static final Logger log = LoggerFactory.getLogger(DynamicVelocityTemplateLoader.class);

    private ISysReportTemplateService templateService;

    @Override
    public void init(ExtProperties configuration) {
        // 延迟初始化
    }

    private ISysReportTemplateService getTemplateService() {
        if (templateService == null) {
            try {
                templateService = SpringUtils.getBean(ISysReportTemplateService.class);
            } catch (Exception e) {
                log.error("无法获取 ISysReportTemplateService Bean", e);
            }
        }
        return templateService;
    }

    @Override
    public Reader getResourceReader(String source, String encoding) throws ResourceNotFoundException {
        if (StrUtil.isBlank(source)) {
            throw new ResourceNotFoundException("Template source is empty");
        }

        // 尝试从数据库获取
        ISysReportTemplateService service = getTemplateService();
        if (service != null) {
            try {
                // source 即为 template code
                SysReportTemplateVo template = service.queryByCode(source);
                if (template != null && StrUtil.isNotBlank(template.getContent())) {
                    log.info(">>>>>> 正在从数据库加载模板: {}", source);
                    return new StringReader(template.getContent());
                }
            } catch (Exception e) {
                log.warn("从数据库加载模板失败: {}", source, e);
            }
        }

        log.info(">>>>>> 数据库未找到模板，将降级到文件系统加载: {}", source);
        throw new ResourceNotFoundException("Template not found in DB: " + source);
    }

    @Override
    public boolean isSourceModified(Resource resource) {
        long lastModified = resource.getLastModified();
        long dbModified = getLastModified(resource);
        return dbModified > lastModified;
    }

    @Override
    public long getLastModified(Resource resource) {
        ISysReportTemplateService service = getTemplateService();
        if (service != null) {
            try {
                SysReportTemplateVo template = service.queryByCode(resource.getName());
                if (template != null && template.getUpdateTime() != null) {
                    return template.getUpdateTime().getTime();
                }
            } catch (Exception e) {
                // ignore
            }
        }
        return 0;
    }
}
