package com.tykj.dev.device.task.service.impl;

import com.tykj.dev.device.task.repository.TaskLogDao;
import com.tykj.dev.device.task.service.TaskLogService;
import com.tykj.dev.device.task.subject.bto.TaskLogBto;
import com.tykj.dev.device.task.subject.domin.TaskLog;
import com.tykj.dev.device.task.subject.vo.TaskLogUserVo;
import com.tykj.dev.device.task.utils.TaskUtils;
import com.tykj.dev.misc.exception.ApiException;
import com.tykj.dev.misc.utils.ResultUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;


/**
 * @author dengdiyi
 */
@Service
public class TaskLogServiceImpl implements TaskLogService {

    @Autowired
    private TaskLogDao taskLogDao;

    @Autowired
    private TaskUtils taskUtils;

    @Override
    public TaskLogBto addLog(TaskLogBto taskLogBto) {
        TaskLog taskLog = taskLogBto.toDo();
        return taskLogDao.save(taskLog).parse2bto();
    }

    @Override
    public TaskLogBto getOne(Integer id) {
        Optional<TaskLog> taskLog = taskLogDao.findById(id);
        if (taskLog.isPresent()){
            return taskLog.get().parse2bto();
        }
        else {
            throw new ApiException(ResultUtil.failed("查询的id不存在"));
        }
    }

    /**
     * @param taskId 业务id
     *               获取业务日志
     */
    @Override
    public List<TaskLogUserVo> getByTaskId(Integer taskId) {
        List<TaskLog> taskLogs = taskUtils.orderByCreateTimeAsc(taskLogDao.getAllByTaskId(taskId));
        return taskLogs.stream().map(TaskLog::parse2bto).map(TaskLogBto::toVo).collect(Collectors.toList());
    }

}
