package com.youlai.boot.system.schedule;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.youlai.boot.common.constant.SystemConstants;
import com.youlai.boot.system.model.entity.Record;
import com.youlai.boot.system.service.ConfigService;
import com.youlai.boot.system.service.RecordService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.time.LocalDateTime;
import java.util.List;

import static com.youlai.boot.common.util.SystemUtil.isLinuxServer;


@Component
@RequiredArgsConstructor
@Slf4j
public class JarStatusTask {

    private final RecordService recordService;

    private final ConfigService configService;





//    @Scheduled(cron = "0 * * * * ?")
//    public void checkJarStatus() {
//
//        if (!isLinuxServer()) return;
//
//        LambdaQueryWrapper<Record> queryWrapper = new LambdaQueryWrapper<>();
//        queryWrapper.eq(Record::getFileType, SystemConstants.JAR_TYPE).eq(Record::getIsDeleted,0);
//        List<Record> jarRecords = recordService.getBaseMapper().selectList(queryWrapper);
//        String jarPath = configService.getSystemConfig("JAVA_PATH").toString();
//        for (Record jarRecord : jarRecords) {
//
//            String command = "ps --no-heading -ef|grep java|grep " +
//                    jarPath +
//                    "|grep " +
//                    jarRecord.getFileName() +
//                    "|awk '{print $2}'";
//
//            String[] commands = {
//                    "/bin/sh", "-c",
//                    command
//            };
//            ProcessBuilder processBuilder = new ProcessBuilder();
//            processBuilder.command(commands);
//
//            try {
//                log.info("execute command: {}",command);
//                Process process = processBuilder.start();
//                // 获取命令执行的输入流（标准输出）
//                BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
//                String pid = reader.readLine();
//                // 等待进程结束并获取退出值
//                int exitCode = process.waitFor();
//                log.info("Exited with code: {}", exitCode);
//                // 输出命令的结果
//
//                jarRecord.setStatus(StringUtils.isBlank(pid)?"0":"1");
//                this.recordService.updateById(jarRecord);
//            } catch (IOException | InterruptedException e) {
//                log.error(e.getMessage(),e);
//            }
//
//        }
//
//
//    }

}
