package cokr.xit.ens.modules.kkomydoc.presentation;

import cokr.xit.ens.core.aop.EnsResponseVO;
import cokr.xit.ens.core.exception.EnsException;
import cokr.xit.ens.core.exception.code.EnsErrCd;
import cokr.xit.ens.modules.kkomydoc.domain.SendDetailKkoMydoc;
import cokr.xit.ens.modules.kkomydoc.domain.repository.SendDetailKkoMydocRepository;
import cokr.xit.ens.modules.kkomydoc.model.KkoMydocAcceptReqDTO;
import cokr.xit.ens.modules.kkomydoc.service.KkoMydocService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.ExampleObject;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

@Tag(name = "KkoMydocController")
@Slf4j
@RequiredArgsConstructor
@RestController
public class KkoMydocController {

    private final KkoMydocService kkoMydocService;
    private final SendDetailKkoMydocRepository sendDetailKkoMydocRepository;


    @Operation(summary = "접수")
    @PostMapping(value = "/kko/mydoc/accept", produces = MediaType.APPLICATION_JSON_VALUE)
//    public ResponseEntity<EnsResponseVO> accept(@Validated @RequestBody KkoMydocAcceptReqDTO reqDTO, BindingResult bindingResult){
    public ResponseEntity<EnsResponseVO> accept(@RequestBody KkoMydocAcceptReqDTO reqDTO) {

//        EnsResponseVO responseVO = null;
//        if (bindingResult.hasErrors()) {
//            List<String> errors = bindingResult.getAllErrors().stream().map(e -> e.getDefaultMessage()).collect(Collectors.toList());
//            responseVO = EnsResponseVO.errRsltBuilder()
//                    .errCode(EnsErrCd.ACPT410)
//                    .errMsg("유효하지 않은 요청값 입니다.")
//                    .resultInfo(errors)
//                    .build();
//        }else{
//            responseVO = kkoMydocService.accept(reqDTO);
//        }
        EnsResponseVO responseVO = kkoMydocService.accept(reqDTO);


        return new ResponseEntity<EnsResponseVO>(responseVO, HttpStatus.OK);
    }


    @io.swagger.v3.oas.annotations.parameters.RequestBody(required = true, content = {
            @Content(mediaType = "application/json", examples = {
                    @ExampleObject(name = "Sample Example..."
                            , summary = "제작"
                            , value = "{\"sendMastId\": 1}")
            })
    })
    @Operation(summary = "제작")
//    @PutMapping(value = "/kko/mydoc/make", produces = MediaType.APPLICATION_JSON_VALUE)
    @PostMapping(value = "/kko/mydoc/make", produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<EnsResponseVO> make(@RequestBody Map<String, Long> mParam) {

        EnsResponseVO responseVO = kkoMydocService.remake(mParam.get("sendMastId"));

        return new ResponseEntity<EnsResponseVO>(responseVO, HttpStatus.OK);
    }


    @Operation(summary = "제작(일괄)")
//    @PutMapping(value = "/kko/mydoc/make/all", produces = MediaType.APPLICATION_JSON_VALUE)
    @PostMapping(value = "/kko/mydoc/make/all", produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<EnsResponseVO> makeAll() {

        EnsResponseVO responseVO = kkoMydocService.makeAll();

        return new ResponseEntity<EnsResponseVO>(responseVO, HttpStatus.OK);
    }


    @io.swagger.v3.oas.annotations.parameters.RequestBody(required = true, content = {
            @Content(mediaType = "application/json", examples = {
                    @ExampleObject(name = "Sample Example..."
                            , summary = "(대량)전송요청"
                            , value = "{\"sendMastId\": 1}")
            })
    })
    @Operation(summary = "(대량)전송요청")
    @PostMapping(value = "/kko/mydoc/send/bulk", produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<EnsResponseVO> sendBulk(@RequestBody Map<String, Long> mParam) {
        EnsResponseVO responseVO = kkoMydocService.sendBulk(mParam.get("sendMastId"));

        return new ResponseEntity<EnsResponseVO>(responseVO, HttpStatus.OK);
    }

    @Operation(summary = "(대량)전송요청 일괄")
    @PostMapping(value = "/kko/mydoc/send/bulk/all", produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<EnsResponseVO> sendBulkAll() {
        EnsResponseVO responseVO = kkoMydocService.sendBulkAll();

        return new ResponseEntity<EnsResponseVO>(responseVO, HttpStatus.OK);
    }


    @io.swagger.v3.oas.annotations.parameters.RequestBody(required = true, content = {
            @Content(mediaType = "application/json", examples = {
                    @ExampleObject(name = "Sample Example..."
                            , summary = "(대량)문서상태 갱신"
                            , value = "{\"sendMastId\": 1}")
            })
    })
    @Operation(summary = "(대량)문서상태 갱신")
//    @PutMapping(value = "/kko/mydoc/stat/bulk", produces = MediaType.APPLICATION_JSON_VALUE)
    @PostMapping(value = "/kko/mydoc/stat/bulk", produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<EnsResponseVO> statBulk(@RequestBody Map<String, Long> mParam) {

        EnsResponseVO responseVO = kkoMydocService.statBulk(mParam.get("sendMastId"));

        return new ResponseEntity<EnsResponseVO>(responseVO, HttpStatus.OK);
    }

    @Operation(summary = "(대량)문서상태 일괄 갱신")
//    @PutMapping(value = "/kko/mydoc/stat/bulk/all", produces = MediaType.APPLICATION_JSON_VALUE)
    @PostMapping(value = "/kko/mydoc/stat/bulk/all", produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<EnsResponseVO> statBulkAll() {

        EnsResponseVO responseVO = kkoMydocService.statBulkAll();

        return new ResponseEntity<EnsResponseVO>(responseVO, HttpStatus.OK);
    }


    @io.swagger.v3.oas.annotations.parameters.RequestBody(required = true, content = {
            @Content(mediaType = "application/json", examples = {
                    @ExampleObject(name = "Sample Example..."
                            , summary = "토큰(OTT) 검증"
                            , value = "{\"document_binder_uuid\": \"BIN-ff806328863311ebb61432ac599d6150\", \"token\": \"ZDU3NGU1ZTYtNTk2Yy99OGNjLWJiYjUtYjZmMjI9NzRhOTA4\", \"external_document_uuid\": \"A0001\"}")
            })
    })
    @Operation(summary = "토큰(OTT) 검증")
    @PostMapping(value = "/kko/mydoc/token/verify", produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<EnsResponseVO> tokenVerify(@RequestBody Map<String, String> mParam) {

        final String documentBinderUuid = mParam.get("document_binder_uuid");
        final String token = mParam.get("token");
        final String externalDocumentUuid = mParam.get("external_document_uuid");


        SendDetailKkoMydoc sendDetail = sendDetailKkoMydocRepository.findFetchByPropExternalDocumentUuidAndDocumentBinderUuid(externalDocumentUuid, documentBinderUuid)
                .orElseThrow(() -> new EnsException(EnsErrCd.ERR404, "문서를 찾을 수 없습니다."));

        EnsResponseVO responseVO = kkoMydocService.tokenVerify(sendDetail.getSendMast().getOrgCd(), documentBinderUuid, token, externalDocumentUuid);

        return new ResponseEntity<EnsResponseVO>(responseVO, HttpStatus.OK);
    }

    @io.swagger.v3.oas.annotations.parameters.RequestBody(required = true, content = {
            @Content(mediaType = "application/json", examples = {
                    @ExampleObject(name = "Sample Example..."
                            , summary = "문서열람 완료처리"
                            , value = "{\"document_binder_uuid\": \"BIN-ff806328863311ebb61432ac599d6150\"}")
            })
    })
    @Operation(summary = "문서열람 완료처리")
    @PostMapping(value = "/kko/mydoc/read/cmplt", produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<EnsResponseVO> readCmplt(@RequestBody Map<String, String> mParam) {

        final String documentBinderUuid = mParam.get("document_binder_uuid");

        SendDetailKkoMydoc sendDetail = sendDetailKkoMydocRepository.findFetchByPropExternalDocumentUuidAndDocumentBinderUuid(null, documentBinderUuid)
                .orElseThrow(() -> new EnsException(EnsErrCd.ERR404, "문서를 찾을 수 없습니다."));

        EnsResponseVO responseVO = kkoMydocService.readCmplt(sendDetail.getSendMast().getOrgCd(), documentBinderUuid);


        return new ResponseEntity<EnsResponseVO>(responseVO, HttpStatus.OK);
    }

    @io.swagger.v3.oas.annotations.parameters.RequestBody(required = true, content = {
            @Content(mediaType = "application/json", examples = {
                    @ExampleObject(name = "Sample Example..."
                            , summary = "전송결과 가져오기"
                            , value = "{\"sendMastId\": 1}")
            })
    })
    @Operation(summary = "전송결과 가져오기")
    @PostMapping(value = "/kko/mydoc/send/result/provide", produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<EnsResponseVO> sendResultProvide(@RequestBody Map<String, Long> mParam) {

        EnsResponseVO responseVO = kkoMydocService.sendResultProvide(mParam.get("sendMastId"));


        return new ResponseEntity<EnsResponseVO>(responseVO, HttpStatus.OK);
    }
}
