
import com.huigou.bpm.webservice.exception.SAPException;
import com.huigou.bpm.webservice.utils.SapJcoUtils;
import com.sap.conn.jco.*;
import com.sap.conn.jco.ext.DestinationDataProvider;
import org.activiti.engine.impl.util.json.JSONObject;
import org.apache.log4j.Logger;

import java.io.File;
import java.io.FileOutputStream;
import java.util.Map;
import java.util.Properties;

public class SapJcoTest {
    public static final Logger logger = Logger.getLogger("cxf.loggingInInterceptor");
    private JCoFunction function;

    // 输入参数列表
    private JCoParameterList inPara = null;

    // 输出参数列表
    private JCoParameterList outPara = null;

    private JCoParameterList tabPara = null;

    private String functionName;

    private static String ABAP_AS ="ABAP_AS_WITHOUT_POOL";

    private JCoDestination destination;

    private SapJcoTest(String portId) throws SAPException {
        connect(); // 连接SAP
    }

    // 调用SapRFC
    public static SapJcoTest getInstance(String portId) throws SAPException, JCoException {
//RFC接口调用开始 ==========
        SapJcoTest common = new SapJcoTest(portId);
        return common;
    }
    // 连接 SAP
    public void connect() throws SAPException {

// set properties参数，
//        String host ="10.15.65.151";
//        String system ="00";
//        String clientName ="401";
//        String userid ="web_con";
//        String password ="web123123";
//        String language ="ZH";
        String host ="192.168.222.22";
        String system ="00";
        String clientName ="800";
        String userid ="lyf";
        String password ="123456";
        String language ="ZH";


// 设置SAP的连接参数
        Properties connectProperties = new Properties();
        connectProperties.setProperty(DestinationDataProvider.JCO_ASHOST, host);
        connectProperties.setProperty(DestinationDataProvider.JCO_SYSNR, system);
        connectProperties.setProperty(DestinationDataProvider.JCO_CLIENT, clientName);
        connectProperties.setProperty(DestinationDataProvider.JCO_USER, userid);
        connectProperties.setProperty(DestinationDataProvider.JCO_PASSWD, password);
        connectProperties.setProperty(DestinationDataProvider.JCO_LANG, language);
        connectProperties.setProperty(DestinationDataProvider.JCO_AUTH_TYPE, "DEV");

        try {
// 创建DestinationDataProvider，
            createDataFile(ABAP_AS,"jcoDestination", connectProperties);
            destination = JCoDestinationManager.getDestination(ABAP_AS);

        } catch (JCoException ex) {
            throw new SAPException("SAP连接失败"+ ex.getMessage());
        }
    }

    /*
     * 设置参数 name - the name of the field to set value - the value to set for the
     * field
     */
    public SapJcoTest addParameter(String name, String value) {
        inPara.setValue(name, value);
        return this;
    }

    public SapJcoTest addParameter(int name, String value) {
        inPara.setValue(name, value);
        return this;
    }

    // 执行方法
    public SapJcoTest prepare(String functionName) throws SAPException {
        this.functionName = functionName;
        try {
// 取得要执行的方法
            function = destination.getRepository().getFunction(functionName);
        } catch (JCoException e) {
            throw new SAPException("SAP获取方法"+ functionName +"失败："+ e.getMessage());
        }
        if (function == null) {
            throw new SAPException(functionName +"方法不存在");
        }
// 取得参数列表
        inPara = function.getImportParameterList();
        outPara = function.getExportParameterList();
        tabPara = function.getTableParameterList();
        logger.info(functionName +"方法调用开始");
        return this;
    }

    // 执行方法
    public JCoParameterList execCall() throws JCoException {
// Execute
        function.execute(destination);
        logger.info(functionName +"方法调用结束");

        return outPara;
    }

    // 取得返回结果
    public JCoTable getResultTable(String tableName) {
        return tabPara.getTable(tableName);
    }

// //取得参数列表
// public JCoTable getParamTable(String tableName) {
// return tabPara.getTable(tableName);
// }

    // SAP传入参数为列表
    public JCoTable getParamTableList(String tableName) {
        return function.getTableParameterList().getTable(tableName);
    }

    // DisConnect
    public void close() {
// if (client != null)
// client.disconnect();
    }


    // Creates a connection configuration file based on parameters given above
    static void createDataFile(String name, String suffix, Properties properties) throws SAPException {
        File cfg = new File(name +"."+ suffix);
// if (!cfg.exists()) {
        try {
            FileOutputStream fos = new FileOutputStream(cfg, false);
            properties.store(fos,"Destination - ABAP_AS_WITHOUT_POOL");
            fos.close();
        } catch (Exception e) {
            throw new SAPException("不能创建SAP连接需要的Destination文件"+ cfg.getName(), e);
        }
//}
    }

    public String convertNull(String str){
        if (str == null)
            return"";
        return str;
    }

    public static void main(String[] args) {
        try {
            SapJcoTest conn = SapJcoTest.getInstance("");
            conn.destination.ping();

//            conn.prepare("Z_BPM2SAP_EXPENDI_AUTHORIZE_SC");
//            conn.prepare("Z_BPM2SAP_PURCHASE_EQUIPMENT");
//            conn.prepare("Z_BPM2SAP_PURCHAS_CONSUMABL");
//            conn.prepare("Z_BPM2SAP_002");
//            conn.prepare("Z_BPM2SAP_BUDGET_QUERY");
//            conn.prepare("Z_BPM2SAP_GET_BUDGET_INFO");
//            conn.prepare("Z_MMF_001");
//            conn.prepare("Z_BPM2SAP_CREATE_VENDOR");
//            conn.prepare("ZMM_GET_EKGRP");
//            conn.prepare("ZMM_GET_LIFNR");
//            conn.prepare("ZMM_GET_EKORG");
//            conn.prepare("ZMM_GET_MATNR");
            conn.prepare("ZMM_BD_PO");

//            conn.addParameter("LIFNR","%%");
//            conn.addParameter("EKGRP","%%");
//            conn.addParameter("EKORG","%%");
            conn.addParameter("MATNR","%%");
            conn.addParameter("WERKS","1100");

            conn.execCall();
            Map<String,Object> obj = SapJcoUtils.list2Map(conn.inPara);
//            Map<String,Object> obj2 = SapJcoUtils.list2Map(conn.outPara);
            Map<String,Object> obj3 = SapJcoUtils.list2Map(conn.tabPara);
            JSONObject obj4 = new JSONObject(obj3);
            System.out.println("调用方法");

//            JCoTable out = conn.tabPara.getTable("OUTPUT_SC");
//            int count = 1;
//            while (out.nextRow()){
//                System.out.println("------------------"+count++);
//                for(int i=0;i<out.getNumColumns();i++){
//                    System.out.println(out.toXML(i));
//                }
//            }


        } catch (SAPException e) {
            e.printStackTrace();
        } catch (JCoException e) {
            e.printStackTrace();
        }
    }
}
