package com.hxhq.business.utils.pdf;

import com.hxhq.common.core.exception.ServiceException;
import com.hxhq.common.core.utils.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.Date;

/**
 * pdf导出基类
 * @author tanfei
 */
@Component
public class PdfExportUtil {

    private static final Logger logger = LoggerFactory.getLogger(PdfExportUtil.class);

    public static Object invokeMethod(String className, String methodName, Object... params)
            throws Exception {
        // 加载类
        Class<?> clazz = Class.forName(className);
        // 创建实例
        Object instance = clazz.getDeclaredConstructor().newInstance();
        // 改为不预先获取参数类型，而是在查找方法时动态匹配
        Method method = null;
        for (Method m : clazz.getMethods()) {
            if (m.getName().equals(methodName)) {
                method = m;
            }
        }

        if (method == null) {
            throw new NoSuchMethodException("找不到匹配的方法: " + methodName);
        }
        // 调用方法
        return method.invoke(instance, params);
    }

    public static void main(String[] args) throws Exception {
        String result = export(
                "com.hxhq.business.utils.pdf.template.sp.Sp001",
                "exportDetail",
                "D:/hxhq/uploadPath"
        );
    }

    /**
     * 导出
     *
     * @param className
     * @param methodName
     * @param params
     * @return
     */
    public static  String export(String className, String methodName, Object... params) {
        try {
            String path= (String) invokeMethod(className, methodName, params);
            return path.replace(params[params.length - 1].toString().replace("/","\\" ), "")
                    .replace("\\", "/");
        } catch (Exception ex) {
            logger.error(ex.getMessage());
            throw new ServiceException(ex.getMessage());
        }
    }

    /**
     * 时间转化
     * @param time
     * @return
     */
    public static String parseDateToStr(Date time){
        return DateUtils.parseDateToStr("yyyy-MM-dd HH:mm:ss",time);
    }

}