package com.oqpo.api.service.rtnmng;



import com.oqpo.api.entity.oper.UserMngEntity;
import com.oqpo.api.entity.pomng.PchOdrDtlPtclEntity;
import com.oqpo.api.entity.rtnmng.RtnOdrBaseInfoEntity;
import com.oqpo.api.entity.rtnmng.RtnOdrDtlPtclEntity;
import com.oqpo.api.entity.rtnmng.RtnReqBaseInfoEntity;
import com.oqpo.api.entity.rtnmng.RtnReqDtlPtclEntity;
import com.oqpo.api.enums.SystemMessageCode;
import com.oqpo.api.exception.GlobalException;
import com.oqpo.api.mapper.inoutmng.ColOdrMapper;
import com.oqpo.api.mapper.loanmng.LoanStateMapper;
import com.oqpo.api.mapper.oper.UserMngMapper;
import com.oqpo.api.mapper.rtnmng.RtnOdrMapper;
import com.oqpo.api.mapper.rtnmng.RtnReqMapper;
import com.oqpo.api.mapper.stinfo.StoreBaseInfoMapper;
import com.oqpo.api.mapper.stockmng.StockMngMapper;
import com.oqpo.api.service.CommonService;
import com.oqpo.api.web.dto.request.GridRequest;
import com.oqpo.api.web.dto.request.pomng.pchOrd.CancelPchOrdDtlRequest;
import com.oqpo.api.web.dto.request.rtnmng.CancelRtnOrdDtlRequest;
import com.oqpo.api.web.dto.request.rtnmng.RtnReqOrdInitRequest;
import com.oqpo.api.web.dto.request.rtnmng.SaveRtnOrdRequest;
import com.oqpo.api.web.dto.response.GridResponse;
import com.oqpo.api.web.dto.response.pomng.pchOrd.PchOdrInfoResponse;
import com.oqpo.api.web.dto.response.pomng.pchOrd.PchOdrSearchListResponse;
import com.oqpo.api.web.dto.response.rtnmng.rtnOrd.RtnOdrInfoResponse;
import com.oqpo.api.web.dto.response.rtnmng.rtnOrd.RtnOdrSearchListResponse;
import com.oqpo.api.web.dto.response.rtnmng.rtnOrd.RtnOrdInitInfoResponse;
import com.oqpo.api.web.dto.response.rtnmng.rtnOrd.RtnOrdNInitInfoResponse;
import com.oqpo.api.web.dto.response.rtnmng.rtnReq.RtnReqInitInfoResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

@Service
@Slf4j
public class RtnOdrService extends CommonService {
    @Autowired
    private RtnOdrMapper rtnOdrMapper;

    @Autowired
    private UserMngMapper userMngMapper;

    @Autowired
    private StockMngMapper stockMngMapper;

    @Autowired
    private RtnReqMapper rtnReqMapper;

    @Autowired
    private ColOdrMapper colOdrMapper;

    @Autowired
    private StoreBaseInfoMapper storeBaseInfoMapper;

    @Autowired
    private LoanStateMapper loanStateMapper;

    @Autowired
    private RtnReqService rtnReqService;



    /* 반품요청건 발주 가능 여부 체크 */

    public String  chkRtnReqUseOrd(String userId, RtnReqOrdInitRequest rtnReqOrdInitRequest ) throws Exception {
        String usePassPoYn = "Y";
        // 초기 발주 head 정보 가져오기
        List<RtnOdrBaseInfoEntity> headList = null;
        List<RtnOdrDtlPtclEntity> itemList = null;

        // 품목 데이타 확인 필요
        List<RtnOdrDtlPtclEntity> gridUpdateData = rtnReqOrdInitRequest.toCodeEntities(rtnReqOrdInitRequest.getGridUpdateData());
        if (gridUpdateData.size() > 0) {
            headList = rtnOdrMapper.selectRecRtnInitInfo(rtnReqOrdInitRequest.getBrandId(),gridUpdateData);
            itemList = rtnOdrMapper.selectRecRtnDtlInitInfo(rtnReqOrdInitRequest.getBrandId(),gridUpdateData);
        }

        if (headList.size() > 1) {
            // 서로다른 수거장소로 인한 처리 불가 오류 메세지 출력  본사출력이면 매장수거장소,,  공급사수거면 본사수거장소
            usePassPoYn = "N";
            throw new GlobalException(SystemMessageCode.ERR_NEQRTNWHSID);
        }

        RtnOdrBaseInfoEntity headData =  headList.get(0);
        String colReqDt = ""; // 수거요청일
        String spplyId = ""; // 공급업체
      //col_dvsn  본사수거  C001 ,  공급사 수거 C002
        if ("C001".equals(headData.getColDvsn())) {
            // 본사수거
            if ("".equals(headData.getStoreId())) {
                usePassPoYn = "N";
                throw new GlobalException(SystemMessageCode.ERR_NONRTNSTORE);
            }
        } else if ("C002".equals(headData.getColDvsn())) {
            // 공급사 수거는 본사 창고입니다.
            for (int i = 0; i < itemList.size(); i++) {
                RtnOdrDtlPtclEntity itemInfo = itemList.get(i);
                if ("".equals(spplyId)) {
                    spplyId = itemInfo.getSpplyId();
                } else {
                    if (!spplyId.equals(itemInfo.getSpplyId())) {
                        usePassPoYn = "N";
                        throw new GlobalException(SystemMessageCode.ERR_NEQRTNSPPLY);
                    }
                }
                if ("".equals(spplyId)) {
                    usePassPoYn = "N";
                    throw new GlobalException(SystemMessageCode.ERR_NONSPPLY);
                }

            }
        }

        return usePassPoYn;
    }


    /* 반품요청 발주  초기 정보
     *
     *
     * */

    public RtnOrdInitInfoResponse selectRecRtnInitInfo(String userId, RtnReqOrdInitRequest rtnReqOrdInitRequest ) throws Exception {

        // 로그인 정보 가져오기
        UserMngEntity uEntity = userMngMapper.selectGroupUserInfo(userId);

        // 초기 발주 head 정보 가져오기
        List<RtnOdrBaseInfoEntity> headList = null;
        List<RtnOdrDtlPtclEntity> itemList = null;

        // 품목 데이타 확인 필요
        List<RtnOdrDtlPtclEntity> gridUpdateData = rtnReqOrdInitRequest.toCodeEntities(rtnReqOrdInitRequest.getGridUpdateData());
        if (gridUpdateData.size() > 0) {
            headList = rtnOdrMapper.selectRecRtnInitInfo(rtnReqOrdInitRequest.getBrandId(),gridUpdateData);
            itemList = rtnOdrMapper.selectRecRtnDtlInitInfo(rtnReqOrdInitRequest.getBrandId(),gridUpdateData);
        }

        if (headList.size() > 1) {
            // 서로다른 수거장소로 인한 처리 불가 오류 메세지 출력  본사출력이면 매장수거장소,,  공급사수거면 본사수거장소
            throw new GlobalException(SystemMessageCode.ERR_NEQRTNWHSID);
        }

        RtnOdrBaseInfoEntity headData =  headList.get(0);
        long rtnTotalAmt = 0 ; // 총 반품금액
        String colReqDt = ""; // 수거요청일
        String spplyId = ""; // 공급업체
        String spplyNm = ""; //공급업체명


        //col_dvsn  본사수거  C001 ,  공급사 수거 C002
        if ("C001".equals(headData.getColDvsn())) {
            if ("".equals(headData.getStoreId())) {
                throw new GlobalException(SystemMessageCode.ERR_NONRTNSTORE);
            }

            for (int j = 0 ; j < itemList.size() ; j++) {
                RtnOdrDtlPtclEntity itemInfo = itemList.get(j);
                rtnTotalAmt = rtnTotalAmt + (itemInfo.getUnitAmt() * itemInfo.getRtnQty());
                colReqDt = itemInfo.getColReqDt() ;
            }

        } else if ("C002".equals(headData.getColDvsn())) {
            // 공급사 수거는 본사 창고입니다.
            for (int i = 0; i < itemList.size(); i++) {
                RtnOdrDtlPtclEntity itemInfo = itemList.get(i);
                rtnTotalAmt = rtnTotalAmt + (itemInfo.getUnitAmt() * itemInfo.getRtnQty());
                colReqDt = itemInfo.getColReqDt() ;
                if ("".equals(spplyId)) {
                    spplyId = itemInfo.getSpplyId();
                    spplyNm = itemInfo.getSpplyNm();
                } else {
                    if (!spplyId.equals(itemInfo.getSpplyId())) {
                        throw new GlobalException(SystemMessageCode.ERR_NEQRTNSPPLY);
                    }
                }
                if ("".equals(spplyId)) {
                    throw new GlobalException(SystemMessageCode.ERR_NONSPPLY);
                }

            }
        }
        // System.out.println(" last==dlvReqDt===================>" + dlvReqDt);
        headData.setSpplyId(spplyId);
        headData.setSpplyNm(spplyNm);
        headData.setRtnDodrTotalAmt(rtnTotalAmt);
        headData.setRtnDodrItemQty(itemList.size());
        headData.setColReqDt(colReqDt);

        return RtnOrdInitInfoResponse.toDTO(uEntity, headData, itemList);
    }

    /*
    반품 발주 신규생성    RtnOrdNInitInfoResponse
*/
    public RtnOrdNInitInfoResponse selectRtnInitInfo(String userId, String brandId) throws Exception {

        // 로그인 정보 가져오기
        UserMngEntity uEntity = userMngMapper.selectGroupUserInfo(userId);

        // 초기 발주 head 정보 가져오기
        RtnOdrBaseInfoEntity headData = rtnOdrMapper.selectRtnInitInfo(brandId);

        return RtnOrdNInitInfoResponse.toDTO(uEntity, headData);
    }

    /*
      발주 정보 저장
*/
    @Transactional
    public void saveRtnOdrInfo(String userId, SaveRtnOrdRequest saveRtnOrdRequest) throws Exception {
        try {

            // 로그인 정보 가져오기
            UserMngEntity uEntity = userMngMapper.selectGroupUserInfo(userId);
            uEntity.setTelNo(uEntity.getTelNo().replaceAll("-",""));
            // 전달받은 데이타와 전송발 데이타 세팅 후 저장
            String rtnPodrUnqNo = fnGetDealNo(19,"");
            RtnOdrBaseInfoEntity rtnOrdEntity = new RtnOdrBaseInfoEntity();

            rtnOrdEntity.setRtnPodrUnqNo(rtnPodrUnqNo);
            rtnOrdEntity.setBrandId(saveRtnOrdRequest.getBrandId());
            rtnOrdEntity.setRtnReqDvsn(saveRtnOrdRequest.getRtnReqDvsn());
            rtnOrdEntity.setRtnMgrNm(uEntity.getUserNm());
            rtnOrdEntity.setRtnMgrId(userId);
            rtnOrdEntity.setRtnMgrTelNo(uEntity.getTelNo());
            rtnOrdEntity.setSpplyId(saveRtnOrdRequest.getSpplyId());
            rtnOrdEntity.setWhsId(saveRtnOrdRequest.getWhsId());
            rtnOrdEntity.setLocation(saveRtnOrdRequest.getLocation());
            rtnOrdEntity.setColDvsn(saveRtnOrdRequest.getColDvsn());
            rtnOrdEntity.setColReqDt(saveRtnOrdRequest.getColReqDt().replaceAll("\\.",""));
            rtnOrdEntity.setStoreId(saveRtnOrdRequest.getStoreId());
            rtnOrdEntity.setRtnWhsId(saveRtnOrdRequest.getRtnWhsId());
            rtnOrdEntity.setRtnLocation(saveRtnOrdRequest.getRtnLocation());

            Integer dtlRow = 0 ;
            List<RtnOdrDtlPtclEntity> rtnOrdDtlList = new ArrayList<RtnOdrDtlPtclEntity>();
            List<RtnOdrDtlPtclEntity> gridUpdateData = saveRtnOrdRequest.toCodeEntities(saveRtnOrdRequest.getGridInsertData());

            // 헤더데이타 체크
            if (gridUpdateData.size() < 1) {
                throw new GlobalException(SystemMessageCode.ERR_NOTITEM);
            }

            List<RtnOdrBaseInfoEntity> headList = rtnOdrMapper.selectRecRtnInitInfo(saveRtnOrdRequest.getBrandId(),gridUpdateData);
            if (headList.size() > 1) {
                // 서로다른 수거장소로 인한 처리 불가 오류 메세지 출력  본사출력이면 매장수거장소,,  공급사수거면 본사수거장소
                throw new GlobalException(SystemMessageCode.ERR_NEQRTNWHSID);
            }

            //List<RtnReqBaseInfoEntity> rtnReqList = new ArrayList<RtnReqBaseInfoEntity>();
            List<RtnReqDtlPtclEntity> rtnReqDtlList = new ArrayList<RtnReqDtlPtclEntity>();
            if (gridUpdateData.size() > 0) {
                long rtnTotAmt = 0 ;
                int rtnItemCnt = 0 ;
                String  diffSpplyYn = "N" ;
                //String  diffStoreYn = "N";
                for (int i = 0 ; i < gridUpdateData.size() ;i++ ) {
                    RtnOdrDtlPtclEntity rtnDtlEntity = gridUpdateData.get(i);  // 전달받은값
                    RtnOdrDtlPtclEntity rtnSaveDtlEntity = new RtnOdrDtlPtclEntity(); // 저장할 메인
                    //RtnReqBaseInfoEntity rtnReqEntity = new RtnReqBaseInfoEntity();  // 반품요청상태
                    RtnReqDtlPtclEntity rtnReqDtlEntity = new RtnReqDtlPtclEntity();  // 반품요청상세상태
                    // 구매요청건에 대한 데이타 가져옴
                    if ("R".equals(saveRtnOrdRequest.getJobCd())) {   // 반품요청건
                        // 구매요청번호와 항번으로 데이타 가져놈

                        rtnSaveDtlEntity = rtnOdrMapper.selectPoRtnDtlSaveInfo(rtnDtlEntity.getRtnReqUnqNo(), rtnDtlEntity.getRtnReqDtlNo());
                        //rtnReqEntity.setRtnReqUnqNo(rtnDtlEntity.getRtnReqUnqNo());
                        //rtnReqEntity.setRtnReqStCd("RR30");
                        rtnReqDtlEntity.setRtnReqUnqNo(rtnDtlEntity.getRtnReqUnqNo());
                        rtnReqDtlEntity.setRtnReqDtlNo(rtnDtlEntity.getRtnReqDtlNo());
                        rtnReqDtlEntity.setRtnReqDtlStCd("RRD30");
                        //rtnReqList.add(rtnReqEntity);
                        rtnReqDtlList.add(rtnReqDtlEntity);

                    } else if ("P".equals(saveRtnOrdRequest.getJobCd())) {  // 신규발주건
                        // item id 로 데이타 가져옴  == 단가는 브랜드 단가로 처리함
                        rtnSaveDtlEntity = rtnOdrMapper.selectRtnItemDtlSaveInfo(saveRtnOrdRequest.getBrandId(), rtnDtlEntity.getItemId(), rtnDtlEntity.getBrandUnitUnqNo());
                    }

                    if (!rtnOrdEntity.getSpplyId().equals(rtnSaveDtlEntity.getSpplyId())) {
                        diffSpplyYn = "Y";  // 수거 공급사는 하나여야 합니다.
                    }

                    dtlRow = dtlRow + 10;
                    rtnSaveDtlEntity.setRtnPodrUnqNo(rtnPodrUnqNo);
                    String dtlNo = Integer.toString(dtlRow);
                    rtnSaveDtlEntity.setRtnPodrDtlNo(dtlNo);
                    rtnSaveDtlEntity.setRtnReqUnqNo(rtnDtlEntity.getRtnReqUnqNo());
                    rtnSaveDtlEntity.setRtnReqDtlNo(rtnDtlEntity.getRtnReqDtlNo());
                    rtnSaveDtlEntity.setRtnQty(rtnDtlEntity.getRtnReqQty());
                    rtnSaveDtlEntity.setRtnAmt(Long.valueOf(rtnDtlEntity.getRtnQty()) * rtnSaveDtlEntity.getUnitAmt() );
                    rtnSaveDtlEntity.setBrandUnitUnqNo(rtnDtlEntity.getBrandUnitUnqNo());
                    rtnSaveDtlEntity.setStoreUnitUnqNo(rtnDtlEntity.getStoreUnitUnqNo());
                    rtnSaveDtlEntity.setRtnDvsn(rtnDtlEntity.getRtnDvsn());
                    rtnSaveDtlEntity.setRtnRsn(rtnDtlEntity.getRtnRsn());
                    rtnSaveDtlEntity.setRtnRsnDvsn(rtnDtlEntity.getRtnRsnDvsn());
                    rtnSaveDtlEntity.setRtnReqQty(rtnDtlEntity.getRtnReqQty());
                    rtnSaveDtlEntity.setRtnOdrAmt(Long.valueOf(rtnDtlEntity.getRtnQty()) * rtnSaveDtlEntity.getUnitAmt());
                    rtnSaveDtlEntity.setRodrDtlStCd("ROD0");

                    rtnTotAmt = rtnTotAmt +  rtnSaveDtlEntity.getRtnOdrAmt();
                    rtnItemCnt = rtnItemCnt + 1;

                    rtnOrdDtlList.add(rtnSaveDtlEntity);
                }

                // 체크로직필요
                if ("C002".equals(rtnOrdEntity.getColDvsn())) {
                    // 공급사 수거일경우
                    // 공급사는 하나여야 함
                    if("".equals(saveRtnOrdRequest.getSpplyId())) {
                        throw new GlobalException(SystemMessageCode.ERR_NOTSPPLY);
                    }

                    if ("Y".equals(diffSpplyYn)) {
                        // 공급사는 하나여야 합니다.
                        throw new GlobalException(SystemMessageCode.ERR_NEQSPPLY);
                    }
                } else {
                    // 브랜드 수거 - 매장
                        if ("".equals(rtnOrdEntity.getStoreId())) {
                            // 매장정보가 없습니다.
                            throw new GlobalException(SystemMessageCode.ERR_NONSTOREID);
                        }



                        //입고창고정보 존재여부 파악
                        if ("".equals(rtnOrdEntity.getWhsId()) || "".equals(rtnOrdEntity.getLocation())) {
                            throw new GlobalException(SystemMessageCode.ERR_INWHS);
                        }
                }

                rtnOrdEntity.setRtnDodrTotalAmt(rtnTotAmt);
                rtnOrdEntity.setRtnDodrItemQty(rtnItemCnt);

                rtnOdrMapper.insertRtnOdrBaseInfo(userId, rtnOrdEntity);
                rtnOdrMapper.insertRtnOdrDtlPtcl(userId, rtnOrdDtlList);


                // 반품요청건에 대한 상태에 대한 처리상태 변경
                if ("R".equals(saveRtnOrdRequest.getJobCd())) {   // 반품요청건
                    rtnReqMapper.updateSelRtnReqDtlStCd(userId,rtnReqDtlList);
                    String rtnReqUnqNo = "";
                    List<RtnReqBaseInfoEntity> rtnReqList = new ArrayList<RtnReqBaseInfoEntity>();
                    for (int k = 0; k < rtnReqDtlList.size(); k++) {
                        if (!rtnReqUnqNo.equals(rtnReqDtlList.get(k).getRtnReqUnqNo())) {
                            rtnReqUnqNo = rtnReqDtlList.get(k).getRtnReqUnqNo();
                            String rtnReqStCd = rtnReqService.selectRtnReqDtlStatusList(rtnReqUnqNo);
                            RtnReqBaseInfoEntity rtnReqEntity = new RtnReqBaseInfoEntity();  // 반품요청상태
                            rtnReqEntity.setRtnReqUnqNo(rtnReqUnqNo);
                            rtnReqEntity.setRtnReqStCd(rtnReqStCd);
                            rtnReqList.add(rtnReqEntity);
                        }
                    }
                    rtnReqMapper.updateRtnReqStCd(userId, rtnReqList);
                }

            }

        } catch (GlobalException e) {
            //e.getStackTrace();
            e.printStackTrace();
            throw new GlobalException(e.getSystemMessageCode());
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException();
        }
    }


    /*
      반품발주 그리드 리스트 조회
*/
    public GridResponse selectRtnOdrGridList(String sBrandId, String fromDt, String toDt, String sRtnOdrStCd, String sRtnWhsId, String sColDvsn, String sWhsId, String sSpplyId, String sItemNm, GridRequest gridRequest) throws Exception {
        int gridPage = gridRequest.getGridPage();
        int gridSize = gridRequest.getGridSize();

        //System.out.println(sBrandId + "==" + fromDt + "==" + toDt + "==" + srtnOdrStCd + "==" + sSpplyId + "==" + sWhsId + "==" + sItemNm);

        fromDt = fromDt == null ? null : fromDt.replace(".", "");
        toDt = toDt == null ? null : toDt.replace(".", "");

        int gridRecords = rtnOdrMapper.selectRtnOdrGridCnt(sBrandId, fromDt, toDt, sRtnOdrStCd,sRtnWhsId, sColDvsn, sWhsId,  sSpplyId,  sItemNm );
        int gridTotal = fnCalculateGridTotal(gridSize, gridRecords);
        List<RtnOdrBaseInfoEntity> entities = rtnOdrMapper.selectRtnOdrGridList(sBrandId, fromDt, toDt, sRtnOdrStCd,sRtnWhsId, sColDvsn, sWhsId,  sSpplyId,  sItemNm, gridRequest);
        List<Object> gridRows = entities.stream()
                .map(m -> RtnOdrSearchListResponse.builder()
                        .viewCd("R")
                        .rtnPodrUnqNo(m.getRtnPodrUnqNo() == null ? "" : m.getRtnPodrUnqNo())
                        .brandId(m.getBrandId() == null ? "" : m.getBrandId())
                        .brandNm(m.getBrandNm() == null ? "" : m.getBrandNm())
                        .rtnOdrStCd(m.getRtnOdrStCd() == null ? "" : m.getRtnOdrStCd())
                        .rtnOdrStNm(m.getRtnOdrStNm() == null ? "" : m.getRtnOdrStNm())
                        .rtnOdrRegDt(m.getRtnOdrRegDt() == null ? "" : m.getRtnOdrRegDt())
                        .rtnWhsId(m.getRtnWhsId() == null ? "" : m.getRtnWhsId())
                        .rtnLocation(m.getRtnLocation() == null ? "" : m.getRtnLocation())
                        .rtnWhsNm(m.getRtnWhsNm() == null ? "" : m.getRtnWhsNm())
                        .rtnLocationNm(m.getRtnLocationNm() == null ? "" : m.getRtnLocationNm())
                        .spplyId(m.getSpplyId() == null ? "" : m.getSpplyId())
                        .spplyNm(m.getSpplyNm() == null ? "" : m.getSpplyNm())
                        .whsId(m.getWhsId() == null ? "" : m.getWhsId())
                        .location(m.getLocation() == null ? "" : m.getLocation())
                        .whsNm(m.getWhsNm() == null ? "" : m.getWhsNm())
                        .locationNm(m.getLocationNm() == null ? "" : m.getLocationNm())
                        .rtnDodrTotalAmt(m.getRtnDodrTotalAmt() == null ? 0 : m.getRtnDodrTotalAmt())
                        .rtnDodrItemQty(m.getRtnDodrItemQty() == null ? 0 : m.getRtnDodrItemQty())
                        .colReqDt(m.getColReqDt() == null ? "" : m.getColReqDt())
                        .colDvsn(m.getColDvsn() == null ? "" : m.getColDvsn())
                        .colDvsnNm(m.getColDvsnNm() == null ? "" : m.getColDvsnNm())
                        .build())
                .collect(Collectors.toList());
        return GridResponse.toDTO(gridPage, gridTotal, gridRecords, gridRows);
    }

    /* 반품발주 정보 */

    public RtnOdrInfoResponse selectrtnOdrInfo(String  rtnPodrUnqNo) throws Exception {
        RtnOdrBaseInfoEntity entity = rtnOdrMapper.selectRtnOdrInfo(rtnPodrUnqNo);
        List<RtnOdrDtlPtclEntity> dtlEntity = rtnOdrMapper.selectROdrDtlList( rtnPodrUnqNo);
        return RtnOdrInfoResponse.toDTO(entity,dtlEntity);
    }


    /*
      반품 발주 취소처리
    */
    @Transactional
    public void cancelRtnOrdDtl(String userId, CancelRtnOrdDtlRequest cancelRtnOrdDtlRequest) throws Exception {
        try {

            // 수거서 생성 여부 파악 (이미생성시 반품 취소 불가)
            int ingCnt = colOdrMapper.selectColRtnIngCnt(cancelRtnOrdDtlRequest.getBrandId(), cancelRtnOrdDtlRequest.getRtnPodrUnqNo());

            if (ingCnt > 0) {
                throw new GlobalException(SystemMessageCode.ERR_INGCOLCNT);
            }

            //반품요청 취소처리
            rtnOdrMapper.updateChgRodrStCd(userId, cancelRtnOrdDtlRequest.getRtnPodrUnqNo(),"RO99");
            rtnOdrMapper.updateChangeRodrDtlStCd(userId, cancelRtnOrdDtlRequest.getRtnPodrUnqNo(),"ROD2");

            RtnOdrBaseInfoEntity rtnOdrInfo = rtnOdrMapper.selectRtnOdrInfo(cancelRtnOrdDtlRequest.getRtnPodrUnqNo());

            // 반품요청건에 대한 상태에 대한 처리상태 변경  RR01
            if ("RR01".equals(rtnOdrInfo.getRtnReqDvsn())) {   // 요청반품건은 반품요청건 상태 변경처리함
                List<RtnOdrDtlPtclEntity> rtnOrdList =  rtnOdrMapper.selectROdrDtlList(cancelRtnOrdDtlRequest.getRtnPodrUnqNo());

                List<RtnReqDtlPtclEntity> rtnReqDtlList = new ArrayList<RtnReqDtlPtclEntity>();
                List<RtnReqBaseInfoEntity> rtnReqBaseList = new ArrayList<RtnReqBaseInfoEntity>();
                String rtnReqUnqNo = "";
                for (int i = 0 ; i < rtnOrdList.size() ;i++) {
                    RtnOdrDtlPtclEntity rtnOdrEntity = rtnOrdList.get(i);
                    RtnReqDtlPtclEntity rtnReqDtlEntity = new RtnReqDtlPtclEntity();
                    RtnReqBaseInfoEntity rtnReqBaseEntity = new RtnReqBaseInfoEntity();

                    rtnReqDtlEntity.setRtnReqUnqNo(rtnOdrEntity.getRtnReqUnqNo());
                    rtnReqDtlEntity.setRtnReqDtlNo(rtnOdrEntity.getRtnReqDtlNo());
                    rtnReqDtlEntity.setRtnReqDtlStCd("RRD99");
                    rtnReqDtlList.add(rtnReqDtlEntity);

                    if (!rtnReqUnqNo.equals(rtnOdrEntity.getRtnReqUnqNo())) {
                        rtnReqUnqNo = rtnOdrEntity.getRtnReqUnqNo();
                        rtnReqBaseEntity.setRtnReqUnqNo(rtnReqUnqNo);

                        String rtnReqStcd = rtnReqService.selectRtnReqDtlStatusList(rtnReqUnqNo);
                        rtnReqBaseEntity.setRtnReqStCd(rtnReqStcd);
                        rtnReqBaseList.add(rtnReqBaseEntity);
                    }
                }
                rtnReqMapper.updateRtnReqStCd(userId,rtnReqBaseList);
            }

        } catch (GlobalException e) {
            //e.getStackTrace();
            e.printStackTrace();
            throw new GlobalException(e.getSystemMessageCode());
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException();
        }
    }

    /*
     공급사 수주현황 리스트

    public GridResponse selectSpplyPoGridList(String sBrandId, String fromDt, String toDt, String sSpplyId, String sWhsId, String srtnOdrStCd, String sItemNm, GridRequest gridRequest) throws Exception {
        int gridPage = gridRequest.getGridPage();
        int gridSize = gridRequest.getGridSize();

        fromDt = fromDt == null ? null : fromDt.replace(".", "");
        toDt = toDt == null ? null : toDt.replace(".", "");

        int gridRecords = pchOrdMapper.selectSpplyPoGridCnt(sBrandId, fromDt, toDt, sSpplyId, sWhsId, srtnOdrStCd, sItemNm);
        int gridTotal = fnCalculateGridTotal(gridSize, gridRecords);
        List<rtnOdrBaseInfoEntity> entities = pchOrdMapper.selectSpplyPoGridList(sBrandId, fromDt, toDt, sSpplyId, sWhsId, srtnOdrStCd, sItemNm, gridRequest);
        List<Object> gridRows = entities.stream()
                .map(m -> SpplyPoOdrSearchListResponse.builder()
                        .viewCd("R")
                        .brandId(m.getBrandId() == null ? "" : m.getBrandId())
                        .brandNm(m.getBrandNm() == null ? "" : m.getBrandNm())
                        .pchPodrUnqNo(m.getPchPodrUnqNo() == null ? "" : m.getPchPodrUnqNo())
                        .rtnOdrStCd(m.getrtnOdrStCd() == null ? "" : m.getrtnOdrStCd())
                        .rtnOdrStNm(m.getrtnOdrStNm() == null ? "" : m.getrtnOdrStNm())
                        .podrDt(m.getPodrDt() == null ? "" : m.getPodrDt())
                        .dlvReqDt(m.getDlvReqDt() == null ? "" : m.getDlvReqDt())
                        .whsNm(m.getWhsNm() == null ? "" : m.getWhsNm() + "-" + m.getLocationNm())
                        .podrTotalAmt(m.getPodrTotalAmt() == null ? 0 : m.getPodrTotalAmt())
                        .podrItemQty(m.getPodrItemQty() == null ? 0 : m.getPodrItemQty())
                        .podrMgrNm(m.getPodrMgrNm() == null ? "" : m.getPodrMgrNm())
                        .build())
                .collect(Collectors.toList());
        return GridResponse.toDTO(gridPage, gridTotal, gridRecords, gridRows);
    }
 */
    /* 구매발주 정보

    public SpplyrtnOdrInfoResponse selectSpplyrtnOdrInfo(String brandId, String  pchReqUnqNo, String spplyId) throws Exception {
        rtnOdrBaseInfoEntity entity = pchOrdMapper.selectSpplyrtnOdrInfo(brandId, pchReqUnqNo, spplyId);
        List<rtnOdrDtlPtclEntity> dtlEntity = pchOrdMapper.selectSpplyOdrDtlList(brandId,  pchReqUnqNo, spplyId);

        return SpplyrtnOdrInfoResponse.toDTO(entity,dtlEntity);
    }
*/

    /* 구매발주에 대한 출고가능수량 정보

    public PchOrdWhsQtyResponse selectWhsPassQty(PchReqOrdPassQtyRequest pchReqOrdPassQtyRequest ) throws Exception {

        List<StckMgntBaseInfoEntity> gridItemData = pchReqOrdPassQtyRequest.toCodeEntities(pchReqOrdPassQtyRequest.getGridUpdateData());

        List<StckMgntBaseInfoEntity> stokList =  stockMngMapper.selectWhsLocOutPassQty(pchReqOrdPassQtyRequest.getBrandId(), pchReqOrdPassQtyRequest.getWhsId(), pchReqOrdPassQtyRequest.getLocation(), gridItemData);

        return PchOrdWhsQtyResponse.toDTO(stokList);
    }
*/
}
