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.IotSapMaterialVO;
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 SyncSapMaterialsJob 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_005");

            // 设置输入参数
            JCoParameterList input = function.getImportParameterList();
            input.setValue("IV_LAEDA", ""); // 上次更改的日期
            input.setValue("IV_MATNR", ""); // 物料编号
            input.setValue("IV_MAKTX", ""); // 物料描述

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

            // 获取输出参数
            JCoParameterList output = function.getTableParameterList();
            JCoTable otItabTable = function.getTableParameterList().getTable("OT_ITAB");
            if (otItabTable != null && otItabTable.getNumRows() > 0) {
                List<IotSapMaterialVO> sapMaterials = new ArrayList<>();
                for (int i = 0; i < otItabTable.getNumRows(); i++) {
                    otItabTable.setRow(i);
                    IotSapMaterialVO tempMaterial = new IotSapMaterialVO();
                    tempMaterial.setMATNR(otItabTable.getString("MATNR"));
                    tempMaterial.setMAKTX(otItabTable.getString("MAKTX"));
                    tempMaterial.setMTART(otItabTable.getString("MTART"));
                    tempMaterial.setMTBEZ(otItabTable.getString("MTBEZ"));
                    tempMaterial.setMATKL(otItabTable.getString("MATKL"));
                    tempMaterial.setWGBEZ(otItabTable.getString("WGBEZ"));
                    tempMaterial.setLVORM(otItabTable.getString("LVORM"));
                    tempMaterial.setMEINS(otItabTable.getString("MEINS"));
                    sapMaterials.add(tempMaterial);
                }
                iotSapService.processMaterials(sapMaterials);
            }
            return "Material Info: " + output.getString("OT_ITAB");
        } catch (JCoException e) {
            return "Error calling SAP Material Master Data: " + e.getMessage();
        }
    }

}
