package com.samsung.sample.approval.internal.controller;

import com.samsung.approval.ApprovalService;
import com.samsung.approval.annotation.ApprovalDocument;
import com.samsung.approval.entity.DynamicApprovalPath;
import com.samsung.approval.entity.RequiredApprovalUser;
import com.samsung.approval.enums.ApprovalDocStatus;
import com.samsung.authentication.Account;
import com.samsung.common.IdGenService;
import com.samsung.core.entity.PagingResult;
import com.samsung.core.exception.KnoxApprovalException;
import com.samsung.resource.FileManagerService;
import com.samsung.sample.approval.internal.InternalApprovalSampleService;
import com.samsung.sample.approval.internal.dto.InternalApprovalSubmitDto;
import com.samsung.sample.approval.internal.dto.InternalSampleSearchDto;
import com.samsung.sample.approval.internal.entity.InternalApprovalSampleDocument;
import com.samsung.template.TemplateConstants;
import com.samsung.user.entity.User;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.support.MessageSourceAccessor;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@RestController
@RequestMapping("/sample/approval/internal")
public class InternalApprovalSampleController {
	
    private final FileManagerService fileManagerService;
    
    private final IdGenService idGenService;
    
    private final InternalApprovalSampleService internalApprovalSampleService;

    private final ApprovalService approvalService;

    private final MessageSourceAccessor messageSourceAccessor;

    public InternalApprovalSampleController(FileManagerService fileManagerService, IdGenService idGenService, InternalApprovalSampleService internalApprovalSampleService, ApprovalService approvalService, MessageSourceAccessor messageSourceAccessor) {
        this.fileManagerService = fileManagerService;
        this.idGenService = idGenService;
        this.internalApprovalSampleService = internalApprovalSampleService;
        this.approvalService = approvalService;
        this.messageSourceAccessor = messageSourceAccessor;
    }

    @Operation(summary = "결재문서 목록 조회(페이징)")
    @GetMapping("/sample-document-with-paging")
    public PagingResult<InternalApprovalSampleDocument> getSampleApprovalDocumentPagingList(
    		@ModelAttribute InternalSampleSearchDto internalSampleSearchDto) {
        return internalApprovalSampleService.getSampleApprovalDocumentPagingList(internalSampleSearchDto);
    }
    
    @Operation(summary = "결재 문서 상세 조회")
    @GetMapping("/sample-documents/{docId}")
    public InternalApprovalSampleDocument getSampleApprovalDocument(
    		@Parameter(description = "문서 ID") @PathVariable String docId) {
    	
    	// 문서 상세정보 조회.
        InternalApprovalSampleDocument internalApprovalSampleDocument = internalApprovalSampleService.getSampleApprovalDocument(docId);
        
        // 결재 상신전 문서의 결재경로, 필수결재자 여부 setting.
        if(ApprovalDocStatus.SAVED.equals(internalApprovalSampleDocument.getDocStatus())) {
        	
        	// 결재 경로 추가(재직중인 사용자만 추가).
            String docType = InternalApprovalSampleDocument.class.getAnnotation(ApprovalDocument.class).docType();
            List<DynamicApprovalPath> dynamicApprovalPathList = approvalService.getDynamicApprovalPath(docType);
            List<DynamicApprovalPath> dynamicApprovalUserList = new ArrayList<>(0);
            
            for(DynamicApprovalPath dynamicApprovalPath : dynamicApprovalPathList) {
            	if("B".equals(dynamicApprovalPath.getEmployeeStatus())) {
            		dynamicApprovalUserList.add(dynamicApprovalPath);
            	}
            }
            
            // 필수 결재자 존재 여부 확인.
            boolean checkExistRequiredApprovalUser = false;
            List<RequiredApprovalUser> requiredApprovalUserList = approvalService.getRequiredApprovalUserList(docType);
            if(!requiredApprovalUserList.isEmpty()) checkExistRequiredApprovalUser = true;
            
            internalApprovalSampleDocument.setDynamicApprovalUserList(dynamicApprovalUserList);
            internalApprovalSampleDocument.setExistRequiredApprovalUser(checkExistRequiredApprovalUser);
            internalApprovalSampleDocument.setRequiredApprovalUserList(requiredApprovalUserList);
        }
        
        internalApprovalSampleDocument.setAttachments(fileManagerService.getAttachFileList(docId, docId));
        
        return internalApprovalSampleDocument;
    }
    
    @Operation(summary = "결재 문서 저장")
    @PostMapping("/sample-documents")
    public InternalApprovalSampleDocument saveDocument(
    		@Parameter(description = "문서 제목") @RequestParam String title,
    		@Parameter(description = "본문")      @RequestParam String contents) {
    	
        InternalApprovalSampleDocument internalApprovalSampleDocument = new InternalApprovalSampleDocument();
        String docId = idGenService.getNextStringId();
        internalApprovalSampleDocument.setDocId(docId);
        internalApprovalSampleDocument.setTitle(title);
        internalApprovalSampleDocument.setContents(contents);
        internalApprovalSampleDocument.setCreator(Objects.requireNonNull(Account.currentUser()).getUserName());

        internalApprovalSampleService.insertSampleApprovalDocument(internalApprovalSampleDocument);
        return internalApprovalSampleDocument;
    }
    
    @Operation(summary = "결재 문서 수정")
    @PutMapping("/sample-documents/{docId}")
    public InternalApprovalSampleDocument modifyDocument(
    		@Parameter(description = "문서 ID") @PathVariable String docId,
    		@Parameter(description = "본문")      @RequestBody InternalApprovalSampleDocument tempDoc) {
    	
        internalApprovalSampleService.modifySampleApprovalDocument(tempDoc);
        fileManagerService.updateFileRefId(docId, tempDoc.getAttachments(), docId);
        return tempDoc;
    }
    
    @Operation(summary = "결재 문서 삭제")
    @DeleteMapping("/sample-documents/{docId}")
    public void deleteDocument(
    		@Parameter(description = "문서 ID") @PathVariable String docId) {

    	InternalApprovalSampleDocument internalApprovalSampleDocument = new InternalApprovalSampleDocument();
    	fileManagerService.updateFileRefId(docId, internalApprovalSampleDocument.getAttachments(), docId);
    	internalApprovalSampleDocument.setDocId(docId);
    	internalApprovalSampleService.deleteSampleApprovalDocument(internalApprovalSampleDocument);
    	fileManagerService.updateFileRefId(docId, null, docId);
    }
    
    @Operation(summary = "결재 문서 상신")
    @PostMapping("/submit/sample-document")
    public void submit(
    		@RequestBody InternalApprovalSubmitDto internalApprovalSubmitDto) {
    	
        if(StringUtils.isEmpty(internalApprovalSubmitDto.getDocId())) throw new KnoxApprovalException("문서 ID는 필수 입니다.");
        if(ObjectUtils.isEmpty(internalApprovalSubmitDto.getApprovalStepList())) throw new KnoxApprovalException("결재 패스는 필수 입니다.");
        
        //결재 문서 조회
        InternalApprovalSampleDocument internalApprovalSampleDocument = internalApprovalSampleService.getSampleApprovalDocument(internalApprovalSubmitDto.getDocId());

        ApprovalDocument approvalDocument = InternalApprovalSampleDocument.class.getAnnotation(ApprovalDocument.class);
        String docType = approvalDocument.docType();
        User requester = Account.currentUser();
        String docId = internalApprovalSampleDocument.getDocId();
        approvalService.submit(docType, internalApprovalSampleDocument.getDocId(), internalApprovalSampleDocument.getTitle(), approvalDocument, null, internalApprovalSubmitDto.getComment(), requester, internalApprovalSubmitDto.getApprovalStepList(),
                TemplateConstants.DOC_NAME, internalApprovalSampleDocument, "attachments", fileManagerService.getAttachFileList(docId, docId), "messages", messageSourceAccessor,
                "internalApproval", approvalDocument.isInternalApproval());
    }

}
