package com.brilliance.isc.doc.handle.impl.common;

import org.slf4j.LoggerFactory;
import org.slf4j.Logger;
import com.brilliance.isc.common.exception.CommonServiceException;
import com.brilliance.isc.common.trndoc.vo.DoceotVo;
import com.brilliance.isc.doc.annotation.DocFunc;
import com.brilliance.isc.doc.handle.ITextProvider;
import com.brilliance.isc.common.doc.TextResultVo;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Map;

public class MethodProvider implements ITextProvider {
    private static Logger logger = LoggerFactory.getLogger(MethodProvider.class);

    /**
     * 面函/报文名称
     */
    private String docName;
    /**
     * 要被执行的方法
     */
    private Method method;
    /**
     * 被执行的组件
     */
    private Object _this;

    public MethodProvider(Object _this,Method method){
        this.method = method;
        this._this = _this;
        DocFunc docFunc = method.getAnnotation(DocFunc.class);
        docName = docFunc.name();
    }

    /**
     * 当前提供的面函模板名称
     *
     * @return
     */
    @Override
    public String getDocName() {
        return docName;
    }

    /**
     * 输出报文结果
     *
     * @param dataBo    数据
     * @param doceotVo  单条面函信息
     * @param extraData 附加的数据
     * @return
     */
    @Override
    public TextResultVo outputMessage(Object dataBo, DoceotVo doceotVo, Map extraData) {
        try {
            return (TextResultVo)this.method.invoke(_this,dataBo,doceotVo);
        } catch (InvocationTargetException e) {
            logger.error("报文生成时发生异常:{}", e.getTargetException());
            throw new CommonServiceException(_this.getClass().getSimpleName() + " invoke method{" + this.method.getName() + "} Occured Exception: " + e.getTargetException().getMessage());
        } catch (Exception e){
            logger.error("报文生成异常：{}",e);
            throw  new CommonServiceException("报文生成异常");
        }
    }

    public Method getMethod() {
        return method;
    }
}
