package com.xvji.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xvji.domain.Component;
import com.xvji.domain.PredictTask;
import com.xvji.mapper.PredictTaskMapper;
import com.xvji.service.ComponentService;
import com.xvji.service.PredictTaskService;
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 PredictTaskServiceImpl extends ServiceImpl<PredictTaskMapper, PredictTask> implements PredictTaskService {

    @Autowired
    private ComponentService componentService;

    /**
     * 新增预测任务并关联组件（事务保证：任务和组件要么同时成功，要么同时失败）
     */
    @Transactional
    @Override
    public boolean addPredictTaskWithComponent(PredictTask predictTask, Component component) {
        // 设置预测任务默认值
        if (predictTask.getPCreateTime() == null) {
            predictTask.setPCreateTime(new Date());
        }
        if (predictTask.getPTaskStatus() == null) {
            predictTask.setPTaskStatus(0); // 0-初始状态
        }

        // 插入预测任务
        boolean taskSaved = this.save(predictTask);
        if (!taskSaved) {
            throw new RuntimeException("预测任务插入失败");
        }

        // 设置关联的任务ID和类型（1-预测任务）
        component.setTaskId(predictTask.getPTaskId());
        component.setTaskType(1);
        if (component.getIsEnable() == null) {
            component.setIsEnable(true);
        }

        // 4. 插入组件
        boolean componentSaved = componentService.save(component);
        if (!componentSaved) {
            throw new RuntimeException("组件插入失败");
        }

        return true;
    }

    @Override
    public List<PredictTask> getAllPredictTasks() {
        return list();
    }


}