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

import cn.iocoder.yudao.framework.quartz.core.handler.JobHandler;
import cn.iocoder.yudao.module.pms.sap.SapConnector;
import cn.iocoder.yudao.module.pms.sap.service.IotSapService;
import cn.iocoder.yudao.module.pms.sap.vo.IotSapMerchantVO;
import com.sap.conn.jco.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * 同步 SAP 客商主数据 定时任务
 */
@Component
@Slf4j
public class SyncSapMerchantJob implements JobHandler {
    @Autowired
    private SapConnector sapConnector;
    @Autowired
    private IotSapService iotSapService;

    /**
     * 暂时只同步当前租户的数据
     * @param param 参数
     * @return
     * @throws Exception
     */
    @Override
    public String execute(String param) throws Exception {
        try {
            JCoDestination destination = sapConnector.getDestination();
            JCoFunction function = destination.getRepository().getFunction("ZPMS_001");

            // 设置输入参数
            JCoParameterList input = function.getImportParameterList();
            input.setValue("CODE", "LFA1"); // 供应商

            // 执行 RFC 调用
            function.execute(destination);

            // 获取输出参数
            JCoParameterList output = function.getTableParameterList();
            JCoTable texportTable = function.getTableParameterList().getTable("TEXPORT");
            if (texportTable != null && texportTable.getNumRows() > 0) {
                List<IotSapMerchantVO> sapMerchants = new ArrayList<>();
                for (int i = 0; i < texportTable.getNumRows(); i++) {
                    texportTable.setRow(i);
                    IotSapMerchantVO tempMerchant = new IotSapMerchantVO();
                    tempMerchant.setCode(texportTable.getString("KV_KEY"));
                    tempMerchant.setName(texportTable.getString("KV_VALUE"));
                    sapMerchants.add(tempMerchant);
                }
                iotSapService.processMerchants(sapMerchants);
            }
            return "Merchant Info: " + output.getString("TEXPORT");
        } catch (JCoException e) {
            return "Error calling SAP Merchant Master Data: " + e.getMessage();
        }
    }

}
