package com.oqpo.api.service.rtnmng;



import com.oqpo.api.entity.inoutmng.*;
import com.oqpo.api.entity.oper.UserMngEntity;
import com.oqpo.api.entity.pomng.PchOdrBaseInfoEntity;
import com.oqpo.api.entity.pomng.PchOdrDtlPtclEntity;
import com.oqpo.api.entity.pomng.PchReqBaseInfoEntity;
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.entity.stockmng.StckMgntBaseInfoEntity;
import com.oqpo.api.entity.stockmng.WhsMgntBaseInfoEntity;
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.mapper.stockmng.WhsMngMapper;
import com.oqpo.api.service.CommonService;
import com.oqpo.api.util.StringUtil;
import com.oqpo.api.web.dto.request.GridRequest;
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.SaveRtnOdrRequest;
import com.oqpo.api.web.dto.request.rtnmng.SaveRtnSteamlineOdrRequest;
import com.oqpo.api.web.dto.response.GridResponse;
import com.oqpo.api.web.dto.response.rtnmng.rtnOrd.*;
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;

    @Autowired
    private WhsMngMapper whsMngMapper;




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

    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 (StringUtil.isEmpty(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 (StringUtil.isEmpty(spplyId)) {
                    spplyId = itemInfo.getSpplyId();
                } else {
                    if (!spplyId.equals(itemInfo.getSpplyId())) {
                        usePassPoYn = "N";
                        throw new GlobalException(SystemMessageCode.ERR_NEQRTNSPPLY);
                    }
                }
                if (StringUtil.isEmpty(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 (StringUtil.isEmpty(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 (StringUtil.isEmpty(spplyId)) {
                    spplyId = itemInfo.getSpplyId();
                    spplyNm = itemInfo.getSpplyNm();
                } else {
                    if (!spplyId.equals(itemInfo.getSpplyId())) {
                        throw new GlobalException(SystemMessageCode.ERR_NEQRTNSPPLY);
                    }
                }
                if (StringUtil.isEmpty(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, SaveRtnOdrRequest saveRtnOdrRequest) 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(saveRtnOdrRequest.getBrandId());
            rtnOrdEntity.setRtnReqDvsn(saveRtnOdrRequest.getRtnReqDvsn());
            rtnOrdEntity.setRtnMgrNm(uEntity.getUserNm());
            rtnOrdEntity.setRtnMgrId(userId);
            rtnOrdEntity.setRtnMgrTelNo(uEntity.getTelNo());
            rtnOrdEntity.setSpplyId(saveRtnOdrRequest.getSpplyId());
            rtnOrdEntity.setWhsId(saveRtnOdrRequest.getWhsId());
            rtnOrdEntity.setLocation(saveRtnOdrRequest.getLocation());
            rtnOrdEntity.setColDvsn(saveRtnOdrRequest.getColDvsn());
            rtnOrdEntity.setColReqDt(saveRtnOdrRequest.getColReqDt().replaceAll("\\.",""));
            rtnOrdEntity.setStoreId(saveRtnOdrRequest.getStoreId());
            rtnOrdEntity.setRtnWhsId(saveRtnOdrRequest.getRtnWhsId());
            rtnOrdEntity.setRtnLocation(saveRtnOdrRequest.getRtnLocation());

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

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

            List<RtnOdrBaseInfoEntity> headList = rtnOdrMapper.selectRecRtnInitInfo(saveRtnOdrRequest.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(saveRtnOdrRequest.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(saveRtnOdrRequest.getJobCd())) {  // 신규발주건
                        // item id 로 데이타 가져옴  == 단가는 브랜드 단가로 처리함
                        rtnSaveDtlEntity = rtnOdrMapper.selectRtnItemDtlSaveInfo(saveRtnOdrRequest.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(rtnSaveDtlEntity.getRtnReqQty());
                    //System.out.println("==========================================");
                    //System.out.println(rtnDtlEntity.getRtnQty() + "===" + rtnSaveDtlEntity.getUnitAmt());
                    //System.out.println("==========================================");
                    if ("C002".equals(saveRtnOdrRequest.getColDvsn())) {
                        rtnSaveDtlEntity.setUnitAmt(rtnSaveDtlEntity.getSpplyUnitAmt());
                    }

                    if ("C002".equals(saveRtnOdrRequest.getColDvsn())) {
                        rtnSaveDtlEntity.setRtnAmt(Long.valueOf(rtnDtlEntity.getRtnQty()) * rtnSaveDtlEntity.getSpplyUnitAmt());
                    } else {
                        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.setRtnOdrQty(rtnDtlEntity.getRtnQty());
                    rtnSaveDtlEntity.setRtnReqQty(rtnDtlEntity.getRtnReqQty());

                    if ("C002".equals(saveRtnOdrRequest.getColDvsn())) {
                        rtnSaveDtlEntity.setRtnOdrAmt(Long.valueOf(rtnDtlEntity.getRtnQty()) * rtnSaveDtlEntity.getSpplyUnitAmt());
                    } else {
                        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(StringUtil.isEmpty(saveRtnOdrRequest.getSpplyId())) {
                        throw new GlobalException(SystemMessageCode.ERR_NOTSPPLY);
                    }

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



                        //입고창고정보 존재여부 파악
                        if (StringUtil.isEmpty(rtnOrdEntity.getWhsId()) || StringUtil.isEmpty(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(saveRtnOdrRequest.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(),"ROD4");

            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 String  selectRtnOdrDtlStatusList(String  rtnPodrUnqNo) throws Exception {
        //PCH_ODR_ST_CD
        String rtnOdrStCd = "";
        List<RtnOdrDtlPtclEntity> dtlEntity = rtnOdrMapper.selectRtnOdrDtlStatusList( rtnPodrUnqNo);

        int rod0 = 0 ;
        int rod1 = 0 ;
        int rod2 = 0 ;
        int rod3 = 0 ;
        int rod4 = 0 ;

        for (int i = 0 ; i < dtlEntity.size() ; i++ ) {
            RtnOdrDtlPtclEntity entity = dtlEntity.get(i);
            if ( "ROD0".equals(entity.getRodrDtlStCd())) {  // 임시저장
                rod0 = rod0 + entity.getRtnStatusCnt() ;
            } else if ( "ROD1".equals(entity.getRodrDtlStCd())) {  // 요청
                rod1 = rod1 + entity.getRtnStatusCnt() ;
            } else if ( "ROD3".equals(entity.getRodrDtlStCd())) {  //접수
                rod3 = rod3 + entity.getRtnStatusCnt() ;
            } else if ( "ROD4".equals(entity.getRodrDtlStCd())) {  //취소
                rod4 = rod4 + entity.getRtnStatusCnt() ;
            }
        }

        if (rod0 > 0 ) {
            rtnOdrStCd = "RO00";  //임시저장
        } else if ( rod0 == 0 && rod1 > 0 ) {
            rtnOdrStCd = "RO20";  // 접수
        } else if ( rod0 == 0 && rod1 == 0 && rod3 > 0 ) {
            rtnOdrStCd = "RO30";  // 취소
        } else {
            rtnOdrStCd = "RO99";  // 취소
        }

        return rtnOdrStCd;
    }

    /*
     공급사 수주현황 리스트
 */
    public GridResponse selectSpplyRtnGridList(String sBrandId, String fromDt, String toDt, String sSpplyId, String sRtnWhsId, 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 = rtnOdrMapper.selectSpplyRtnOdrGridCnt(sBrandId,sSpplyId,  fromDt, toDt, sRtnOdrStCd, sRtnWhsId, sItemNm);
        int gridTotal = fnCalculateGridTotal(gridSize, gridRecords);
        List<RtnOdrBaseInfoEntity> entities = rtnOdrMapper.selectSpplyRtnOdrGridList(sBrandId,sSpplyId,  fromDt, toDt, sRtnOdrStCd, sRtnWhsId, sItemNm, gridRequest);
        List<Object> gridRows = entities.stream()
                .map(m -> SpplyRtnOdrSearchListResponse.builder()
                        .viewCd("R")
                        .brandId(m.getBrandId() == null ? "" : m.getBrandId())
                        .brandNm(m.getBrandNm() == null ? "" : m.getBrandNm())
                        .rtnPodrUnqNo(m.getRtnPodrUnqNo() == null ? "" : m.getRtnPodrUnqNo())
                        .rtnOdrStCd(m.getRtnOdrStCd() == null ? "" : m.getRtnOdrStCd())
                        .rtnOdrStNm(m.getRtnOdrStNm() == null ? "" : m.getRtnOdrStNm())
                        .rtnOdrRegDt(m.getRtnOdrRegDt() == null ? "" : m.getRtnOdrRegDt())
                        .colReqDt(m.getColReqDt() == null ? "" : m.getColReqDt())
                        .rtnWhsNm(m.getRtnWhsNm() == null ? "" : m.getRtnWhsNm() + "-" + m.getRtnLocationNm())
                        .rtnDodrTotalAmt(m.getRtnDodrTotalAmt() == null ? 0 : m.getRtnDodrTotalAmt())
                        .rtnDodrItemQty(m.getRtnDodrItemQty() == null ? 0 : m.getRtnDodrItemQty())
                        .rtnMgrNm(m.getRtnMgrNm() == null ? "" : m.getRtnMgrNm())
                        .build())
                .collect(Collectors.toList());
        return GridResponse.toDTO(gridPage, gridTotal, gridRecords, gridRows);
    }

    /*
     발주 정보 저장
*/
    @Transactional
    public void saveRtnSteamlineOdrInfo(String userId, SaveRtnSteamlineOdrRequest saveRtnSteamlineOdrRequest) throws Exception {
        try {

            // 로그인 정보 가져오기
            UserMngEntity uEntity = userMngMapper.selectGroupUserInfo(userId);
            uEntity.setTelNo(uEntity.getTelNo().replaceAll("-",""));

            List<RtnReqBaseInfoEntity> gridInsertData = saveRtnSteamlineOdrRequest.toCodeEntities(saveRtnSteamlineOdrRequest.getGridInsertData());

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

            // 기본창고 여부 확인 (본사배송 건 존재시 기본창고 여부 확인 하여 없을 경우 오류 처리 있으면 그냥 진행
            int brandColCnt = rtnOdrMapper.selectPchRtnStreamlineBrandColChk(saveRtnSteamlineOdrRequest.getBrandId(), gridInsertData);
            WhsMgntBaseInfoEntity whsEntity = null ;

            if (brandColCnt > 0 ) {
                // 기본창고 및 로케이션 있는지 여부 확인
                int baseWhsCnt = whsMngMapper.selectBaseWhsLocationCnt(saveRtnSteamlineOdrRequest.getBrandId()) ;

                if (baseWhsCnt > 0 ) {
                    whsEntity = whsMngMapper.selectBaseWhsLocationInfo(saveRtnSteamlineOdrRequest.getBrandId()) ;
                } else {
                    //오류 처리 (창고관리에서 기본창고를 지정해주세요!)
                    throw new GlobalException(SystemMessageCode.ERR_NON_BASE_WHS);
                }
            }

            //처리 내역 저장 구분
            RtnOdrBaseInfoEntity tempTargetBase =  null ; //new RtnOdrBaseInfoEntity();
            List<RtnOdrBaseInfoEntity> tempTargetBaseList = new ArrayList<RtnOdrBaseInfoEntity>();
            RtnOdrDtlPtclEntity tempTargetPtcl = null ; //new RtnOdrDtlPtclEntity();
            List<RtnOdrDtlPtclEntity> tempTargetPtclList = new ArrayList<RtnOdrDtlPtclEntity>();

            ColOdrBaseEntity colBaseEntity = null ; //new ColOdrBaseEntity();
            List<ColOdrBaseEntity> colBaseList = new ArrayList<ColOdrBaseEntity>();
            ColOdrDtlPtclEntity colOdrDtlEntity = null ; //new ColOdrDtlPtclEntity();
            List<ColOdrDtlPtclEntity> colDtlList = new ArrayList<ColOdrDtlPtclEntity>();

            PickInfoMgntEntity pickBaseEntity = null; //new PickInfoMgntEntity();
            List<PickInfoMgntEntity> pickBaseList = new ArrayList<PickInfoMgntEntity>();
            PickDtlPtclEntity pickDtlEntity = null ; //new PickDtlPtclEntity();
            List<PickDtlPtclEntity> pickDtlList = new ArrayList<PickDtlPtclEntity>();

            for (int i = 0 ; i < gridInsertData.size() ; i++) {
                RtnReqBaseInfoEntity rtnReqEntity = gridInsertData.get(i);
                // 반품요청번호로 반품요청 내역 가져오기
                List<RtnOdrBaseInfoEntity> rtnOrdList = rtnOdrMapper.selectPchRtnStreamlineList(saveRtnSteamlineOdrRequest.getBrandId(),rtnReqEntity.getRtnReqUnqNo());

                String preColDvsn = "";
                String preSpplyId = "";
                String rtnPodrUnqNo = ""; //구매발주번호
                String colCmdUnqNo = ""; // 수거지시번호
                String colPickUnqNo = ""; // 수거서번호
                int dtlRow = 0 ;
                long rtnTotAmt = 0 ;
                int rtnItemCnt = 0 ;

                for (int j = 0 ; j < rtnOrdList.size() ; j++) {
                    // 구매요청건에 대한 개별 처리 방안
                    RtnOdrBaseInfoEntity rtnPodrEntity = rtnOrdList.get(j);

                    //기존거와 동일 여부 체크
                    if (preColDvsn.equals(rtnPodrEntity.getColDvsn())) {
                        if ("C001".equals(rtnPodrEntity.getColDvsn())) { //본사수거
                            tempTargetPtcl = new RtnOdrDtlPtclEntity();
                            dtlRow = dtlRow + 10;
                            tempTargetPtcl.setRtnPodrUnqNo(rtnPodrUnqNo);
                            tempTargetPtcl.setRtnPodrDtlNo(Integer.toString(dtlRow));
                            tempTargetPtcl.setRtnReqUnqNo(rtnPodrEntity.getRtnOdrDtlInfo().getRtnReqUnqNo());
                            tempTargetPtcl.setRtnReqDtlNo(rtnPodrEntity.getRtnOdrDtlInfo().getRtnReqDtlNo());
                            tempTargetPtcl.setItemId(rtnPodrEntity.getRtnOdrDtlInfo().getItemId());
                            tempTargetPtcl.setItemNm(rtnPodrEntity.getRtnOdrDtlInfo().getItemNm());
                            tempTargetPtcl.setUnit(rtnPodrEntity.getRtnOdrDtlInfo().getUnit());
                            tempTargetPtcl.setUnitAmt(rtnPodrEntity.getRtnOdrDtlInfo().getUnitAmt());
                            tempTargetPtcl.setColReqDt(rtnPodrEntity.getColReqDt());
                            tempTargetPtcl.setRtnReqQty(rtnPodrEntity.getRtnOdrDtlInfo().getRtnQty());
                            tempTargetPtcl.setRtnDvsn(rtnPodrEntity.getRtnOdrDtlInfo().getRtnDvsn());
                            tempTargetPtcl.setRtnAmt(rtnPodrEntity.getRtnOdrDtlInfo().getRtnAmt());
                            tempTargetPtcl.setRtnRsnDvsn(rtnPodrEntity.getRtnOdrDtlInfo().getRtnRsnDvsn());
                            tempTargetPtcl.setRtnRsn(rtnPodrEntity.getRtnOdrDtlInfo().getRtnRsn());
                            tempTargetPtcl.setRtnOdrQty(rtnPodrEntity.getRtnOdrDtlInfo().getRtnOdrQty());
                            tempTargetPtcl.setRtnOdrAmt(rtnPodrEntity.getRtnOdrDtlInfo().getRtnOdrAmt());
                            tempTargetPtcl.setRodrDtlStCd("ROD3");
                            tempTargetPtclList.add(tempTargetPtcl);
                            rtnTotAmt = rtnTotAmt +  rtnPodrEntity.getRtnOdrDtlInfo().getRtnAmt();
                            rtnItemCnt = rtnItemCnt + 1;


                            colOdrDtlEntity = new ColOdrDtlPtclEntity();
                            colOdrDtlEntity.setColCmdUnqNo(colCmdUnqNo);
                            colOdrDtlEntity.setColCmdDtlNo(Integer.toString(dtlRow));
                            colOdrDtlEntity.setColCmdDtlStCd("CDLD1");
                            colOdrDtlEntity.setItemId(rtnPodrEntity.getRtnOdrDtlInfo().getItemId());
                            colOdrDtlEntity.setItemNm(rtnPodrEntity.getRtnOdrDtlInfo().getItemNm());
                            colOdrDtlEntity.setUnitAmt(rtnPodrEntity.getRtnOdrDtlInfo().getUnitAmt());
                            colOdrDtlEntity.setColQty(rtnPodrEntity.getRtnOdrDtlInfo().getRtnQty());
                            colOdrDtlEntity.setColAmt(rtnPodrEntity.getRtnOdrDtlInfo().getRtnAmt());
                            colOdrDtlEntity.setRtnQty(rtnPodrEntity.getRtnOdrDtlInfo().getRtnOdrQty());
                            colOdrDtlEntity.setRtnAmt(rtnPodrEntity.getRtnOdrDtlInfo().getRtnOdrAmt());
                            colOdrDtlEntity.setRtnRsnDvsn(rtnPodrEntity.getRtnOdrDtlInfo().getRtnRsnDvsn());
                            colOdrDtlEntity.setRtnRsn(rtnPodrEntity.getRtnOdrDtlInfo().getRtnRsn());
                            colOdrDtlEntity.setRtnPodrUnqNo(rtnPodrUnqNo);
                            colOdrDtlEntity.setRtnPodrDtlNo(Integer.toString(dtlRow));
                            colOdrDtlEntity.setRtnReqUnqNo(rtnPodrEntity.getRtnOdrDtlInfo().getRtnReqUnqNo());
                            colOdrDtlEntity.setRtnReqDtlNo(rtnPodrEntity.getRtnOdrDtlInfo().getRtnReqDtlNo());
                            colDtlList.add(colOdrDtlEntity);

                            pickDtlEntity = new PickDtlPtclEntity();

                            pickDtlEntity.setColPickUnqNo(colPickUnqNo);
                            pickDtlEntity.setColPickDtlNo(Integer.toString(dtlRow));
                            pickDtlEntity.setRtnPodrUnqNo(rtnPodrUnqNo);
                            pickDtlEntity.setRtnPodrDtlNo(Integer.toString(dtlRow));
                            pickDtlEntity.setRtnReqUnqNo(rtnPodrEntity.getRtnOdrDtlInfo().getRtnReqUnqNo());
                            pickDtlEntity.setRtnReqDtlNo(rtnPodrEntity.getRtnOdrDtlInfo().getRtnReqDtlNo());
                            pickDtlEntity.setColCmdUnqNo(colCmdUnqNo);
                            pickDtlEntity.setColCmdDtlNo(Integer.toString(dtlRow));
                            pickDtlEntity.setPickDtlStCd("PICKD0");
                            pickDtlEntity.setItemId(rtnPodrEntity.getRtnOdrDtlInfo().getItemId());
                            pickDtlEntity.setItemNm(rtnPodrEntity.getRtnOdrDtlInfo().getItemNm());
                            pickDtlEntity.setUnit(rtnPodrEntity.getRtnOdrDtlInfo().getUnit());
                            pickDtlEntity.setUnitAmt(rtnPodrEntity.getRtnOdrDtlInfo().getUnitAmt());
                            pickDtlEntity.setRodrQty(rtnPodrEntity.getRtnOdrDtlInfo().getRtnOdrQty());
                            pickDtlEntity.setColReqQty(rtnPodrEntity.getRtnOdrDtlInfo().getRtnOdrQty());
                            pickDtlEntity.setColReqAmt(rtnPodrEntity.getRtnOdrDtlInfo().getRtnOdrAmt());

                            pickDtlList.add(pickDtlEntity);

                        } else { //공급사 수거
                            if (preSpplyId.equals(rtnPodrEntity.getSpplyId())) {
                                 // 공급사 동일할 경우
                                tempTargetPtcl = new RtnOdrDtlPtclEntity();
                                dtlRow = dtlRow + 10;
                                tempTargetPtcl.setRtnPodrUnqNo(rtnPodrUnqNo);
                                tempTargetPtcl.setRtnPodrDtlNo(Integer.toString(dtlRow));
                                tempTargetPtcl.setRtnReqUnqNo(rtnPodrEntity.getRtnOdrDtlInfo().getRtnReqUnqNo());
                                tempTargetPtcl.setRtnReqDtlNo(rtnPodrEntity.getRtnOdrDtlInfo().getRtnReqDtlNo());
                                tempTargetPtcl.setItemId(rtnPodrEntity.getRtnOdrDtlInfo().getItemId());
                                tempTargetPtcl.setItemNm(rtnPodrEntity.getRtnOdrDtlInfo().getItemNm());
                                tempTargetPtcl.setUnit(rtnPodrEntity.getRtnOdrDtlInfo().getUnit());
                                tempTargetPtcl.setUnitAmt(rtnPodrEntity.getRtnOdrDtlInfo().getSpplyUnitAmt());
                                tempTargetPtcl.setColReqDt(rtnPodrEntity.getColReqDt());
                                tempTargetPtcl.setRtnReqQty(rtnPodrEntity.getRtnOdrDtlInfo().getRtnQty());
                                tempTargetPtcl.setRtnDvsn(rtnPodrEntity.getRtnOdrDtlInfo().getRtnDvsn());
                                tempTargetPtcl.setRtnAmt(rtnPodrEntity.getRtnOdrDtlInfo().getRtnQty() * rtnPodrEntity.getRtnOdrDtlInfo().getSpplyUnitAmt());
                                tempTargetPtcl.setRtnRsnDvsn(rtnPodrEntity.getRtnOdrDtlInfo().getRtnRsnDvsn());
                                tempTargetPtcl.setRtnRsn(rtnPodrEntity.getRtnOdrDtlInfo().getRtnRsn());
                                tempTargetPtcl.setRtnOdrQty(rtnPodrEntity.getRtnOdrDtlInfo().getRtnOdrQty());
                                tempTargetPtcl.setRtnOdrAmt(rtnPodrEntity.getRtnOdrDtlInfo().getRtnQty()  * rtnPodrEntity.getRtnOdrDtlInfo().getSpplyUnitAmt());
                                tempTargetPtcl.setRodrDtlStCd("ROD1");
                                tempTargetPtclList.add(tempTargetPtcl);
                                rtnTotAmt = rtnTotAmt +  ( rtnPodrEntity.getRtnOdrDtlInfo().getRtnQty()  * rtnPodrEntity.getRtnOdrDtlInfo().getSpplyUnitAmt() );
                                rtnItemCnt = rtnItemCnt + 1;
                            } else {
                                //공급사 상이 신규추가
                                if (!"".toString().equals(preColDvsn)) {
                                    tempTargetBase.setRtnDodrTotalAmt(rtnTotAmt);
                                    tempTargetBase.setRtnDodrItemQty(rtnItemCnt);
                                    tempTargetBaseList.add(tempTargetBase);

                                    if ("C001".equals(preColDvsn)) {
                                        colBaseEntity.setColTotalAmt(rtnTotAmt);
                                        colBaseEntity.setItemQty(rtnItemCnt);
                                        pickBaseEntity.setColTotAmt(rtnTotAmt);
                                        colBaseList.add(colBaseEntity);
                                        pickBaseList.add(pickBaseEntity);
                                    }
                                }

                                rtnTotAmt = 0 ;
                                rtnItemCnt = 0 ;
                                tempTargetBase = new RtnOdrBaseInfoEntity();
                                tempTargetPtcl = new RtnOdrDtlPtclEntity();
                                preSpplyId = rtnPodrEntity.getSpplyId();

                                // 전달받은 데이타와 전송발 데이타 세팅 후 저장
                                rtnPodrUnqNo = fnGetDealNo(19,"");

                                tempTargetBase.setRtnPodrUnqNo(rtnPodrUnqNo);
                                preColDvsn = rtnPodrEntity.getColDvsn();
                                preSpplyId = rtnPodrEntity.getSpplyId();
                                tempTargetBase.setBrandId(saveRtnSteamlineOdrRequest.getBrandId());
                                tempTargetBase.setRtnOdrRegDt(rtnPodrEntity.getRtnOdrRegDt());
                                tempTargetBase.setRtnReqDvsn(rtnPodrEntity.getRtnReqDvsn());
                                tempTargetBase.setRtnMgrNm(uEntity.getUserNm());
                                tempTargetBase.setRtnMgrId(userId);
                                tempTargetBase.setRtnMgrTelNo(uEntity.getTelNo());
                                tempTargetBase.setSpplyId(rtnPodrEntity.getSpplyId());
                                tempTargetBase.setColDvsn(rtnPodrEntity.getColDvsn());
                                tempTargetBase.setColReqDt(rtnPodrEntity.getColReqDt());
                                tempTargetBase.setStoreId(rtnPodrEntity.getStoreId());
                                tempTargetBase.setRtnWhsId(rtnPodrEntity.getRtnWhsId());
                                tempTargetBase.setRtnLocation(rtnPodrEntity.getRtnLocation());
                                tempTargetBase.setRtnOdrStCd("RO20");

                                dtlRow = 10;
                                tempTargetPtcl.setRtnPodrUnqNo(rtnPodrUnqNo);
                                tempTargetPtcl.setRtnPodrDtlNo(Integer.toString(dtlRow));
                                tempTargetPtcl.setRtnReqUnqNo(rtnPodrEntity.getRtnOdrDtlInfo().getRtnReqUnqNo());
                                tempTargetPtcl.setRtnReqDtlNo(rtnPodrEntity.getRtnOdrDtlInfo().getRtnReqDtlNo());
                                tempTargetPtcl.setItemId(rtnPodrEntity.getRtnOdrDtlInfo().getItemId());
                                tempTargetPtcl.setItemNm(rtnPodrEntity.getRtnOdrDtlInfo().getItemNm());
                                tempTargetPtcl.setUnit(rtnPodrEntity.getRtnOdrDtlInfo().getUnit());
                                tempTargetPtcl.setUnitAmt(rtnPodrEntity.getRtnOdrDtlInfo().getSpplyUnitAmt());
                                tempTargetPtcl.setColReqDt(rtnPodrEntity.getColReqDt());
                                tempTargetPtcl.setRtnReqQty(rtnPodrEntity.getRtnOdrDtlInfo().getRtnQty());
                                tempTargetPtcl.setRtnDvsn(rtnPodrEntity.getRtnOdrDtlInfo().getRtnDvsn());
                                tempTargetPtcl.setRtnAmt(rtnPodrEntity.getRtnOdrDtlInfo().getRtnQty() * rtnPodrEntity.getRtnOdrDtlInfo().getSpplyUnitAmt());
                                tempTargetPtcl.setRtnRsnDvsn(rtnPodrEntity.getRtnOdrDtlInfo().getRtnRsnDvsn());
                                tempTargetPtcl.setRtnRsn(rtnPodrEntity.getRtnOdrDtlInfo().getRtnRsn());
                                tempTargetPtcl.setRtnOdrQty(rtnPodrEntity.getRtnOdrDtlInfo().getRtnOdrQty());
                                tempTargetPtcl.setRtnOdrAmt(rtnPodrEntity.getRtnOdrDtlInfo().getRtnOdrQty() * rtnPodrEntity.getRtnOdrDtlInfo().getSpplyUnitAmt());
                                tempTargetPtcl.setRodrDtlStCd("ROD1");
                                tempTargetPtclList.add(tempTargetPtcl);
                                rtnTotAmt = rtnTotAmt +  ( rtnPodrEntity.getRtnOdrDtlInfo().getRtnOdrQty() * rtnPodrEntity.getRtnOdrDtlInfo().getSpplyUnitAmt());
                                rtnItemCnt = rtnItemCnt + 1;
                            }
                        }
                    } else {
                        //신규 추가 처리
                        if (!"".toString().equals(preColDvsn)) {
                            tempTargetBase.setRtnDodrTotalAmt(rtnTotAmt);
                            tempTargetBase.setRtnDodrItemQty(rtnItemCnt);
                            tempTargetBaseList.add(tempTargetBase);

                            if ("C001".equals(preColDvsn)) {
                                colBaseEntity.setColTotalAmt(rtnTotAmt);
                                colBaseEntity.setItemQty(rtnItemCnt);
                                pickBaseEntity.setColTotAmt(rtnTotAmt);
                                colBaseList.add(colBaseEntity);
                                pickBaseList.add(pickBaseEntity);
                            }
                        }

                        rtnTotAmt = 0 ;
                        rtnItemCnt = 0 ;
                        tempTargetBase = new RtnOdrBaseInfoEntity();
                        tempTargetPtcl = new RtnOdrDtlPtclEntity();

                        // 전달받은 데이타와 전송발 데이타 세팅 후 저장
                        rtnPodrUnqNo = fnGetDealNo(19,"");

                        tempTargetBase.setRtnPodrUnqNo(rtnPodrUnqNo);
                        tempTargetBase.setRtnOdrStCd("RO20");
                        preColDvsn = rtnPodrEntity.getColDvsn();
                        preSpplyId = rtnPodrEntity.getSpplyId();
                        tempTargetBase.setBrandId(saveRtnSteamlineOdrRequest.getBrandId());
                        tempTargetBase.setRtnOdrRegDt(rtnPodrEntity.getRtnOdrRegDt());
                        tempTargetBase.setRtnReqDvsn(rtnPodrEntity.getRtnReqDvsn());
                        tempTargetBase.setRtnMgrNm(uEntity.getUserNm());
                        tempTargetBase.setRtnMgrId(userId);
                        tempTargetBase.setRtnMgrTelNo(uEntity.getTelNo());
                        tempTargetBase.setSpplyId(rtnPodrEntity.getSpplyId());
                        tempTargetBase.setColDvsn(rtnPodrEntity.getColDvsn());
                        tempTargetBase.setColReqDt(rtnPodrEntity.getColReqDt());
                        tempTargetBase.setStoreId(rtnPodrEntity.getStoreId());
                        tempTargetBase.setRtnWhsId(rtnPodrEntity.getRtnWhsId());
                        tempTargetBase.setRtnLocation(rtnPodrEntity.getRtnLocation());

                        dtlRow = 10;
                        tempTargetPtcl.setRtnPodrUnqNo(rtnPodrUnqNo);
                        tempTargetPtcl.setRodrDtlStCd("ROD1");
                        tempTargetPtcl.setRtnPodrDtlNo(Integer.toString(dtlRow));
                        tempTargetPtcl.setRtnReqUnqNo(rtnPodrEntity.getRtnOdrDtlInfo().getRtnReqUnqNo());
                        tempTargetPtcl.setRtnReqDtlNo(rtnPodrEntity.getRtnOdrDtlInfo().getRtnReqDtlNo());
                        tempTargetPtcl.setItemId(rtnPodrEntity.getRtnOdrDtlInfo().getItemId());
                        tempTargetPtcl.setItemNm(rtnPodrEntity.getRtnOdrDtlInfo().getItemNm());
                        tempTargetPtcl.setUnit(rtnPodrEntity.getRtnOdrDtlInfo().getUnit());
                        if ("C001".equals(rtnPodrEntity.getColDvsn())) {
                            tempTargetPtcl.setUnitAmt(rtnPodrEntity.getRtnOdrDtlInfo().getUnitAmt());
                        } else {
                            tempTargetPtcl.setUnitAmt(rtnPodrEntity.getRtnOdrDtlInfo().getSpplyUnitAmt());
                        }


                        tempTargetPtcl.setColReqDt(rtnPodrEntity.getColReqDt());
                        tempTargetPtcl.setRtnReqQty(rtnPodrEntity.getRtnOdrDtlInfo().getRtnQty());
                        tempTargetPtcl.setRtnDvsn(rtnPodrEntity.getRtnOdrDtlInfo().getRtnDvsn());
                        tempTargetPtcl.setRtnAmt(rtnPodrEntity.getRtnOdrDtlInfo().getRtnAmt());

                        if ("C001".equals(rtnPodrEntity.getColDvsn())) {
                            tempTargetPtcl.setRtnAmt(rtnPodrEntity.getRtnOdrDtlInfo().getRtnAmt());
                        } else {
                            tempTargetPtcl.setRtnAmt(rtnPodrEntity.getRtnOdrDtlInfo().getRtnQty() * rtnPodrEntity.getRtnOdrDtlInfo().getSpplyUnitAmt());
                        }

                        tempTargetPtcl.setRtnRsnDvsn(rtnPodrEntity.getRtnOdrDtlInfo().getRtnRsnDvsn());
                        tempTargetPtcl.setRtnRsn(rtnPodrEntity.getRtnOdrDtlInfo().getRtnRsn());
                        tempTargetPtcl.setRtnOdrQty(rtnPodrEntity.getRtnOdrDtlInfo().getRtnOdrQty());
                        if ("C001".equals(rtnPodrEntity.getColDvsn())) {
                            tempTargetPtcl.setRtnOdrAmt(rtnPodrEntity.getRtnOdrDtlInfo().getRtnOdrAmt());
                        } else {
                            tempTargetPtcl.setRtnOdrAmt(rtnPodrEntity.getRtnOdrDtlInfo().getRtnOdrQty() * rtnPodrEntity.getRtnOdrDtlInfo().getSpplyUnitAmt());
                        }


                        tempTargetPtclList.add(tempTargetPtcl);
                        if ("C001".equals(rtnPodrEntity.getColDvsn())) {
                            rtnTotAmt = rtnTotAmt + rtnPodrEntity.getRtnOdrDtlInfo().getRtnAmt();
                        } else {
                            rtnTotAmt = rtnTotAmt + rtnPodrEntity.getRtnOdrDtlInfo().getRtnQty() * rtnPodrEntity.getRtnOdrDtlInfo().getSpplyUnitAmt();
                        }

                        rtnItemCnt = rtnItemCnt + 1;

                        //본사수거일경우 수거지시 , 수거서 생성 처리함
                        if ("C001".equals(rtnPodrEntity.getColDvsn())) {
                            tempTargetBase.setRtnOdrStCd("RO30");
                            tempTargetPtcl.setRodrDtlStCd("ROD3");
                            tempTargetBase.setWhsId(whsEntity.getWhsId());
                            tempTargetBase.setLocation(whsEntity.getLocationInfo().getLocation());

                            colBaseEntity = new ColOdrBaseEntity();
                            colOdrDtlEntity = new ColOdrDtlPtclEntity();
                            pickBaseEntity = new PickInfoMgntEntity();
                            pickDtlEntity = new PickDtlPtclEntity();

                            colCmdUnqNo = fnGetDealNo(20, "");  // 수거지시번호
                            colPickUnqNo = fnGetDealNo(15, ""); // 수거서번호

                            colBaseEntity.setColCmdUnqNo(colCmdUnqNo);
                            colBaseEntity.setColRegDt(rtnPodrEntity.getRtnOdrRegDt());
                            colBaseEntity.setBrandId(saveRtnSteamlineOdrRequest.getBrandId());
                            colBaseEntity.setWhsId(whsEntity.getWhsId());
                            colBaseEntity.setLocation(whsEntity.getLocationInfo().getLocation());
                            colBaseEntity.setStoreId(rtnPodrEntity.getStoreId());
                            colBaseEntity.setColReqDt(rtnPodrEntity.getRtnOdrRegDt());
                            colBaseEntity.setColDvsn(rtnPodrEntity.getColDvsn());
                            colBaseEntity.setColCmdStCd("COL1");
                            colBaseEntity.setColReqMgrNm(uEntity.getUserNm());
                            colBaseEntity.setColReqMgrId(userId);
                            colBaseEntity.setColDt(null);
                            colBaseEntity.setColCnfmNm(null);
                            colBaseEntity.setColCnfmId(null);
                            colBaseEntity.setColMgrNm(uEntity.getUserNm());
                            colBaseEntity.setColMgrTelNo(uEntity.getTelNo());
                            colBaseEntity.setColMgrEmal(null);
                            colBaseEntity.setColMgrMblNo(null);
                            colBaseEntity.setRtnWhsId(rtnPodrEntity.getRtnWhsId());
                            colBaseEntity.setRtnLocation(rtnPodrEntity.getRtnLocation());
                            colBaseEntity.setColPickUnqNo(colPickUnqNo);
                            colBaseEntity.setSpplyId(rtnPodrEntity.getSpplyId());
                            colBaseEntity.setSpplyNm(rtnPodrEntity.getSpplyNm());
                            //colBaseList.add(colBaseEntity);

                            colOdrDtlEntity.setColCmdUnqNo(colCmdUnqNo);
                            colOdrDtlEntity.setColCmdDtlNo(Integer.toString(dtlRow));
                            colOdrDtlEntity.setColCmdDtlStCd("CDLD1");
                            colOdrDtlEntity.setItemId(rtnPodrEntity.getRtnOdrDtlInfo().getItemId());
                            colOdrDtlEntity.setItemNm(rtnPodrEntity.getRtnOdrDtlInfo().getItemNm());
                            colOdrDtlEntity.setUnitAmt(rtnPodrEntity.getRtnOdrDtlInfo().getUnitAmt());
                            colOdrDtlEntity.setColQty(rtnPodrEntity.getRtnOdrDtlInfo().getRtnQty());
                            colOdrDtlEntity.setColAmt(rtnPodrEntity.getRtnOdrDtlInfo().getRtnAmt());
                            colOdrDtlEntity.setRtnQty(rtnPodrEntity.getRtnOdrDtlInfo().getRtnOdrQty());
                            colOdrDtlEntity.setRtnAmt(rtnPodrEntity.getRtnOdrDtlInfo().getRtnOdrAmt());
                            colOdrDtlEntity.setRtnRsnDvsn(rtnPodrEntity.getRtnOdrDtlInfo().getRtnRsnDvsn());
                            colOdrDtlEntity.setRtnRsn(rtnPodrEntity.getRtnOdrDtlInfo().getRtnRsn());
                            colOdrDtlEntity.setRtnPodrUnqNo(rtnPodrUnqNo);
                            colOdrDtlEntity.setRtnPodrDtlNo(Integer.toString(dtlRow));
                            colOdrDtlEntity.setRtnReqUnqNo(rtnPodrEntity.getRtnOdrDtlInfo().getRtnReqUnqNo());
                            colOdrDtlEntity.setRtnReqDtlNo(rtnPodrEntity.getRtnOdrDtlInfo().getRtnReqDtlNo());
                            colDtlList.add(colOdrDtlEntity);

                            pickBaseEntity.setColPickUnqNo(colPickUnqNo);
                            pickBaseEntity.setSpplyId(rtnPodrEntity.getSpplyId());
                            pickBaseEntity.setSpplyNm(rtnPodrEntity.getSpplyNm());
                            pickBaseEntity.setStoreId(rtnPodrEntity.getStoreId());
                            pickBaseEntity.setColRegDt(rtnPodrEntity.getRtnOdrRegDt());
                            pickBaseEntity.setPickMgrNm(uEntity.getUserNm());
                            pickBaseEntity.setPickMgrTelNo(uEntity.getTelNo());
                            pickBaseEntity.setPndrTelNo(whsEntity.getMgrTelNo());
                            pickBaseEntity.setPickStCd("PICK0");
                            pickBaseEntity.setRodrRegDt(rtnPodrEntity.getRtnOdrRegDt());
                            pickBaseEntity.setColReqDt(rtnPodrEntity.getRtnOdrRegDt());
                            pickBaseEntity.setColSchDt(rtnPodrEntity.getRtnOdrRegDt());
                            pickBaseEntity.setColCmpltDt(null);
                            pickBaseEntity.setWhsId(rtnPodrEntity.getRtnWhsId());
                            pickBaseEntity.setLocation(rtnPodrEntity.getRtnLocation());
                            pickBaseEntity.setBrandId(saveRtnSteamlineOdrRequest.getBrandId());
                            pickBaseEntity.setColDesc(null);
                            pickBaseEntity.setColDvsn(rtnPodrEntity.getColDvsn());
                            pickBaseEntity.setWhsDvsn("C001".equals(rtnPodrEntity.getColDvsn()) ? "W02" : "W01");
                            //pickBaseList.add(pickBaseEntity);

                            pickDtlEntity.setColPickUnqNo(colPickUnqNo);
                            pickDtlEntity.setColPickDtlNo(Integer.toString(dtlRow));
                            pickDtlEntity.setRtnPodrUnqNo(rtnPodrUnqNo);
                            pickDtlEntity.setRtnPodrDtlNo(Integer.toString(dtlRow));
                            pickDtlEntity.setRtnReqUnqNo(rtnPodrEntity.getRtnOdrDtlInfo().getRtnReqUnqNo());
                            pickDtlEntity.setRtnReqDtlNo(rtnPodrEntity.getRtnOdrDtlInfo().getRtnReqDtlNo());
                            pickDtlEntity.setColCmdUnqNo(colCmdUnqNo);
                            pickDtlEntity.setColCmdDtlNo(Integer.toString(dtlRow));
                            pickDtlEntity.setPickDtlStCd("PICKD0");
                            pickDtlEntity.setItemId(rtnPodrEntity.getRtnOdrDtlInfo().getItemId());
                            pickDtlEntity.setItemNm(rtnPodrEntity.getRtnOdrDtlInfo().getItemNm());
                            pickDtlEntity.setUnit(rtnPodrEntity.getRtnOdrDtlInfo().getUnit());
                            pickDtlEntity.setUnitAmt(rtnPodrEntity.getRtnOdrDtlInfo().getUnitAmt());
                            pickDtlEntity.setRodrQty(rtnPodrEntity.getRtnOdrDtlInfo().getRtnOdrQty());
                            pickDtlEntity.setColReqQty(rtnPodrEntity.getRtnOdrDtlInfo().getRtnOdrQty());
                            pickDtlEntity.setColReqAmt(rtnPodrEntity.getRtnOdrDtlInfo().getRtnOdrAmt());

                            pickDtlList.add(pickDtlEntity);


                        } else {
                            tempTargetBase.setRtnOdrStCd("RO20");
                            tempTargetPtcl.setRodrDtlStCd("ROD1");
                        }
                    }

                    //마지막 부분 추가 하기
                    if (j == rtnOrdList.size()-1) {
                        tempTargetBase.setRtnDodrTotalAmt(rtnTotAmt);
                        tempTargetBase.setRtnDodrItemQty(rtnItemCnt);
                        tempTargetBaseList.add(tempTargetBase);
                        if ("C001".equals(preColDvsn)) {
                            colBaseEntity.setColTotalAmt(rtnTotAmt);
                            colBaseEntity.setItemQty(rtnItemCnt);
                            pickBaseEntity.setColTotAmt(rtnTotAmt);
                            colBaseList.add(colBaseEntity);
                            pickBaseList.add(pickBaseEntity);
                        }
                    }

                } // 반품요청건 for문 종료


            } // for문 종결


            // 발주 생성
            rtnOdrMapper.insertStreamlineRtnOdrBaseInfo(userId, tempTargetBaseList);
            rtnOdrMapper.insertStremalineRtnOdrDtlPtcl(userId, tempTargetPtclList);
            //반품요청 상태 업데이트
            rtnReqMapper.updateStreamListRtnReqDtlStCd(userId,gridInsertData );
            rtnReqMapper.updateStreamListRtnReqStCd(userId,gridInsertData );

            if (colBaseList.size() > 0 ) {
                colOdrMapper.insertStreamlineColOdrBase(userId, colBaseList);
                colOdrMapper.insertColOdrDtl(userId, colDtlList);
                colOdrMapper.insertStreamlinePickMgntBase(userId, pickBaseList);
                colOdrMapper.insertPickDtlPtcl(userId, pickDtlList);
            }

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

}
