package com.junmp.jyzb.kettle.controller;

import com.junmp.jyzb.kettle.bean.KettleParamReq;
import com.junmp.v2.common.bean.response.ApiRes;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.pentaho.di.core.KettleEnvironment;
import org.pentaho.di.core.exception.KettleException;
import org.pentaho.di.job.Job;
import org.pentaho.di.job.JobMeta;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;


@RestController
@RequestMapping("/kettleSpoon")
@Api(value = "KETTLESPOON API",tags = "[数据抽取]数据抽取接口")
@Slf4j
public class kettleController {


    @PostMapping("/policeOrBoxUpdate")
    public ApiRes<Boolean> policeOrBoxUpdate(@RequestBody KettleParamReq req){
        try {

            File jobFile = new File(req.getJobPath());
            if (!jobFile.exists()) {
                return ApiRes.failure("Error: KJB file not found at path: " + req.getJobPath());
            }

//             创建作业元数据对象
            JobMeta jobMeta = new JobMeta(req.getJobPath(), null);

            // 创建作业并执行
            Job job = new Job(null, jobMeta);
            job.start();
            job.waitUntilFinished();

            // 检查执行结果
            if (job.getErrors() > 0) {
                return ApiRes.failure("Kettle job execution failed with " + job.getErrors() + " errors");
            } else {
                return ApiRes.success();
            }
        } catch (KettleException e) {
            e.printStackTrace();
            return ApiRes.failure("Error executing Kettle job: " + e.getMessage());
        }
    }
}
