package cn.iocoder.yudao.module.pms.sap;

import com.sap.conn.jco.*;
import com.sap.conn.jco.ext.DestinationDataProvider;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import java.io.File;
import java.io.FileOutputStream;
import java.util.Properties;

@Component
public class SapConnector {
    private static final String DEST_NAME = "SAP_DEST";
    @Value("${sap.jco.ashost}") private String ashost;
    @Value("${sap.jco.sysnr}") private String sysnr;
    @Value("${sap.jco.client}") private String client;
    @Value("${sap.jco.user}") private String user;
    @Value("${sap.jco.passwd}") private String passwd;
    @Value("${sap.jco.lang}") private String lang;
    @Value("${sap.jco.pool-capacity}") private String poolCapacity;
    @Value("${sap.jco.peak-limit}") private String peakLimit;

    public JCoDestination getDestination() throws JCoException {
        Properties props = new Properties();
        props.setProperty(DestinationDataProvider.JCO_ASHOST, ashost);
        props.setProperty(DestinationDataProvider.JCO_SYSNR, sysnr);
        props.setProperty(DestinationDataProvider.JCO_CLIENT, client);
        props.setProperty(DestinationDataProvider.JCO_USER, user);
        props.setProperty(DestinationDataProvider.JCO_PASSWD, passwd);
        props.setProperty(DestinationDataProvider.JCO_LANG, lang);
        props.setProperty(DestinationDataProvider.JCO_POOL_CAPACITY, poolCapacity);
        props.setProperty(DestinationDataProvider.JCO_PEAK_LIMIT, peakLimit);

        // 生成连接配置文件
        createDestinationFile(DEST_NAME, props);
        return JCoDestinationManager.getDestination(DEST_NAME);
    }

    private void createDestinationFile(String destName, Properties props) {
        File destFile = new File(destName + ".jcoDestination");
        try (FileOutputStream fos = new FileOutputStream(destFile)) {
            props.store(fos, "SAP Connection Config");
        } catch (Exception e) {
            throw new RuntimeException("Failed to create SAP destination file", e);
        }
    }
}