package com.izouma.jmrh.service;

import com.izouma.jmrh.domain.Approval;
import com.izouma.jmrh.domain.ApprovalProcess;
import com.izouma.jmrh.enums.ApprovalProcessStatus;
import com.izouma.jmrh.enums.ApprovalStatus;
import com.izouma.jmrh.exception.BusinessException;
import com.izouma.jmrh.repo.ApprovalProcessRepo;
import com.izouma.jmrh.repo.ApprovalRepo;
import com.izouma.jmrh.utils.SecurityUtils;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;

import javax.transaction.Transactional;
import java.time.LocalDateTime;

@Service
@AllArgsConstructor
public class ApprovalService {

    private ApprovalRepo           approvalRepo;
    private ApprovalProcessRepo    approvalProcessRepo;
    private ApprovalProcessService approvalProcessService;

    @Transactional
    public ApprovalProcess create(Approval record) {
        if (record.getApprover1() == null || record.getApprover1().isEmpty()) {
            throw new BusinessException("请选择一级审批人");
        }

        record.setCreator(SecurityUtils.getAuthenticatedUser().getUsername());
        record.setCurrentApprover(SecurityUtils.getAuthenticatedUser().getUsername());
        record.setStatus(ApprovalStatus.DRAFT);
        record = approvalRepo.save(record);

        ApprovalProcess process = approvalProcessRepo.save(ApprovalProcess.builder()
                .approvalId(record.getId())
                .approval(record)
                .userId(SecurityUtils.getAuthenticatedUser().getId())
                .approver(SecurityUtils.getAuthenticatedUser().getUsername())
                .level(0)
                .status(ApprovalProcessStatus.PENDING)
                .build());

        return process;
    }
}
