package com.xvji.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
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);
    }

    /**
     * 查询所有训练任务
     */
    @Override
    public List<TrainTask> getAllTrainTasks() {
        return baseMapper.selectList(null);
    }

    /**
     * 根据id删除训练任务 同时删除关联组件
     * @param taskId 训练任务id
     * @return
     */
    @Transactional
    @Override
    public boolean deleteTrainTaskWithComponents(Long taskId) {

        TrainTask trainTask = this.getById(taskId);
        if (trainTask == null){
            //没有此id任务
            return false;
        }
        QueryWrapper<Component> componentQueryWrapper = new QueryWrapper<>();
        componentQueryWrapper
                .eq("TASK_ID",taskId)
                .eq("TASK_TYPE",0);//训练任务类型为0
        componentService.remove(componentQueryWrapper);//删除任务相关组件
        this.removeById(taskId);
        return true;

    }
}