package com.xvji.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xvji.domain.Component;
import com.xvji.domain.TrainTask;
import com.xvji.mapper.TrainTaskMapper;
import com.xvji.service.ComponentService;
import com.xvji.service.TrainTaskService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * 训练任务服务
 */
@Service
public class TrainTaskServiceImpl extends ServiceImpl<TrainTaskMapper, TrainTask> implements TrainTaskService {

    @Autowired
    private ComponentService componentService;

    /**
     * 新增训练任务并关联单个组件
     * 默认填充任务创建时间、任务状态
     */
    @Transactional
    @Override
    public boolean addTrainTaskWithComponent(TrainTask trainTask, Component component) {
        if (trainTask.getTCreateTime() == null) {
            trainTask.setTCreateTime(new Date()); // 默认当前时间
        }
        if (trainTask.getTTaskStatus() == null) {
            trainTask.setTTaskStatus(0); // 默认初始状态（1-成功，0-失败）
        }

        // 保存训练任务
        boolean taskSaved = this.save(trainTask);
        if (!taskSaved) {
            throw new RuntimeException("训练任务保存失败");
        }

        component.setTaskId(trainTask.getTTaskId());
        component.setTaskType(0);
        if (component.getIsEnable() == null) {
            component.setIsEnable(true); // 组件默认启用
        }
        return componentService.save(component);
    }

    /**
     * 查询所有训练任务（直接调用Mapper的查询方法，可根据需求扩展条件）
     */
    @Override
    public List<TrainTask> getAllTrainTasks() {
        return baseMapper.selectList(null);
    }
}