package com.zjty.tynotes.job.basic.service.impl;

import com.zjty.tynotes.job.basic.entity.database.Work;
import com.zjty.tynotes.job.basic.repository.WorkRepository;
import com.zjty.tynotes.job.basic.service.PriviceService;
import com.zjty.tynotes.job.common.exception.NotFoundException;
import com.zjty.tynotes.pas.service.IUserService;
import org.reactivestreams.Publisher;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class PriviceServiceImpl implements PriviceService {
    @Autowired
    WorkRepository workRepository;
    @Autowired
    IUserService iUserService;
    @Override
    public Work findByWorkIdWorkVo(String superoirId) {
        return superoirIdWork(superoirId);
    }

    /**
     * 递归调用查询主任务
     * @param superoirId 上级任务id
     * @return work对象
     */
    private Work superoirIdWork(String superoirId){
        if (!workRepository.existsById(superoirId)){
            throw new NotFoundException(String.format("[job] id为 %s 的任务不存在.", superoirId));
        }
        Work work= workRepository.findById(superoirId).get();
        if (work.getSuperiorId()==null|| "".equals(work.getSuperiorId())){
           String publisherName = iUserService.findUserById(work.getPublisher()).getUsername();
           String executorName = iUserService.findUserById(work.getExecutor()).getUsername();
           work.setPublisher(publisherName);
           work.setExecutor(executorName);
            return work;
        }else {
            return  superoirIdWork(work.getSuperiorId());
        }

    }
}
