package com.oqpo.api.service.pomng;


import com.oqpo.api.entity.loanmng.LoanMgntBaseInfoEntity;
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.pomng.PchReqDtlPtclEntity;
import com.oqpo.api.entity.stockmng.StckMgntBaseInfoEntity;
import com.oqpo.api.enums.SystemMessageCode;
import com.oqpo.api.exception.GlobalException;
import com.oqpo.api.mapper.loanmng.LoanStateMapper;
import com.oqpo.api.mapper.oper.UserMngMapper;
import com.oqpo.api.mapper.pomng.PchOrdMapper;
import com.oqpo.api.mapper.pomng.PchReqMapper;
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.pomng.pchOrd.PchReqOrdInitRequest;
import com.oqpo.api.web.dto.request.pomng.pchOrd.SavePchOrdRequest;
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.pomng.pchOrd.PchOrdInitInfoResponse;
import com.oqpo.api.web.dto.response.pomng.pchOrd.PoOrdInitInfoResponse;
import com.oqpo.api.web.dto.response.pomng.pchReq.PchReqInfoResponse;
import com.oqpo.api.web.dto.response.pomng.pchReq.PchReqSearchListResponse;
import lombok.extern.slf4j.Slf4j;
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 PchOrdService extends CommonService {
    @Autowired
    private PchOrdMapper pchOrdMapper;

    @Autowired
    private UserMngMapper userMngMapper;

    @Autowired
    private StockMngMapper stockMngMapper;

    @Autowired
    private PchReqMapper pchReqMapper;

    @Autowired
    private StoreBaseInfoMapper storeBaseInfoMapper;

    @Autowired
    private LoanStateMapper loanStateMapper;


    /* 구매요청건 발주 가능 여부 체크 */
    public String  chkPchReqUseOrd(String userId, PchReqOrdInitRequest pchReqOrdInitRequest ) throws Exception {
        String usePassPoYn = "Y";
        // 초기 발주 head 정보 가져오기
        List<PchOdrBaseInfoEntity> headList = null;
        List<PchOdrDtlPtclEntity> itemList = null;

        // 품목 데이타 확인 필요
        List<PchOdrDtlPtclEntity> gridUpdateData = pchReqOrdInitRequest.toCodeEntities(pchReqOrdInitRequest.getGridUpdateData());
        if (gridUpdateData.size() > 0) {
            headList = pchOrdMapper.selectRecPchInitInfo(pchReqOrdInitRequest.getBrandId(),gridUpdateData);
            itemList = pchOrdMapper.selectRecPchDtlInitInfo(pchReqOrdInitRequest.getBrandId(),gridUpdateData);
        }

        if (headList.size() > 1) {
            // 서로다른 납품장소로 인한 처리 불가 오류 메세지 출력
            usePassPoYn = "N";
            throw new GlobalException(SystemMessageCode.ERR_NEQWHSID);
        }

        PchOdrBaseInfoEntity headData =  headList.get(0);
        String dlvReqDt = ""; // 납품요청일
        String spplyId = ""; // 공급업체

        if ("DL01".equals(headData.getDlvDvsn())) {
              // 본사 배송은 매장으로의 배송이며, 납품장소는 매장이어야 함
              // 구매요청건이 같은 매장이어야 하며, 납품요청일 동일해야함
            if ("".equals(headData.getStoreId())) {
                usePassPoYn = "N";
                throw new GlobalException(SystemMessageCode.ERR_NONSTORE);
            }

            for (int j = 0 ; j < itemList.size() ; j++) {
                PchOdrDtlPtclEntity itemInfo = itemList.get(j);
                if ("".equals(dlvReqDt)) {
                    dlvReqDt = itemInfo.getDlvReqDt();
                } else {
                    if (!dlvReqDt.equals(itemInfo.getDlvReqDt())) {
                        usePassPoYn = "N";
                        throw new GlobalException(SystemMessageCode.ERR_NEQDLVDT);
                    }
                }
            }
        } else if ("DL02".equals(headData.getDlvDvsn())) {
            // 납품매장으로 - 공급사 배송에서 본사로 배송
            for (int i = 0; i < itemList.size(); i++) {
                PchOdrDtlPtclEntity itemInfo = itemList.get(i);
                if ("".equals(spplyId)) {
                    spplyId = itemInfo.getSpplyId();
                } else {
                    if (!spplyId.equals(itemInfo.getSpplyId())) {
                        usePassPoYn = "N";
                        throw new GlobalException(SystemMessageCode.ERR_NEQSPPLY);
                    }
                }
                if ("".equals(spplyId)) {
                    usePassPoYn = "N";
                    throw new GlobalException(SystemMessageCode.ERR_NONSPPLY);
                }

            }
        }

        return usePassPoYn;
    }


    /* 구매요청 발주  초기 정보
    *
    * 1. 구매요청에서 선택된 품목에 대해 발주 대상 품목 가능 여부 - 납품장소가 매장이면  납품요청일 + , 납품장소가 본사창고이면 납품요청일 + 납품공급사 ㅇ여부 체크하고 이상없을시
    *     발주생성화면으로 전환
    * 2. 발주 초기데이타에 대해 한번더 점검한후 발주생성 --
    * */

    public PchOrdInitInfoResponse selectRecPchInitInfo(String userId, PchReqOrdInitRequest pchReqOrdInitRequest ) throws Exception {

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

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

        // 품목 데이타 확인 필요
        List<PchOdrDtlPtclEntity> gridUpdateData = pchReqOrdInitRequest.toCodeEntities(pchReqOrdInitRequest.getGridUpdateData());
        if (gridUpdateData.size() > 0) {
            headList = pchOrdMapper.selectRecPchInitInfo(pchReqOrdInitRequest.getBrandId(),gridUpdateData);
            itemList = pchOrdMapper.selectRecPchDtlInitInfo(pchReqOrdInitRequest.getBrandId(),gridUpdateData);
        }

        if (headList.size() > 1) {
            // 서로다른 납품장소로 인한 처리 불가 오류 메세지 출력
            throw new GlobalException(SystemMessageCode.ERR_NEQWHSID);
        }

        PchOdrBaseInfoEntity headData =  headList.get(0);
        int podrTotalAmt = 0 ; // 총 발주금액
        String dlvReqDt = ""; // 납품요청일
        String spplyId = ""; // 공급업체
        String spplyNm = ""; //공급업체명


        if ("DL01".equals(headData.getDlvDvsn())) {
            // 본사에서 매장으로 배송처리
            if ("".equals(headData.getStoreId())) {
                throw new GlobalException(SystemMessageCode.ERR_NONSTORE);
            }

            for (int j = 0 ; j < itemList.size() ; j++) {
                PchOdrDtlPtclEntity itemInfo = itemList.get(j);
                podrTotalAmt = podrTotalAmt + (itemInfo.getUnitAmt() * itemInfo.getPchReqQty());
                if ("".equals(dlvReqDt)) {
                    dlvReqDt = itemInfo.getDlvReqDt();
                } else {
                    if (!dlvReqDt.equals(itemInfo.getDlvReqDt())) {
                        throw new GlobalException(SystemMessageCode.ERR_NEQDLVDT);
                    }
                }
            }
        } else if ("DL02".equals(headData.getDlvDvsn())) {
            // 매장으로 납품 (본사에서 발송할지 공급사에서 발송할지 여부 판단. 기본은 본사에서 발송처리되어지도록 함)
            for (int i = 0 ; i < itemList.size() ;i++) {
                PchOdrDtlPtclEntity itemInfo = itemList.get(i);
                podrTotalAmt = podrTotalAmt + (itemInfo.getUnitAmt() * itemInfo.getPchReqQty());
                if ("".equals(spplyId)) {
                    spplyId = itemInfo.getSpplyId();
                    spplyNm = itemInfo.getSpplyNm();
                } else {
                    if (!spplyId.equals(itemInfo.getSpplyId())) {
                        throw new GlobalException(SystemMessageCode.ERR_NEQSPPLY);
                    }
                }
                if ("".equals(spplyId)) {
                    throw new GlobalException(SystemMessageCode.ERR_NONSPPLY);
                }
            }
        }

        headData.setSpplyId(spplyId);
        headData.setSpplyNm(spplyNm);
        headData.setPodrTotalAmt(podrTotalAmt);


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

    /*
    발주 신규생성 초기데이타
     */
    public PoOrdInitInfoResponse selectPoInitInfo(String userId, String brandId) throws Exception {

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

        // 초기 발주 head 정보 가져오기
        PchOdrBaseInfoEntity headData = pchOrdMapper.selectPoInitInfo(brandId);

        return PoOrdInitInfoResponse.toDTO(uEntity, headData);
    }

    /*
      발주 정보 저장
     */
    @Transactional
    public void savePchOrdInfo(String userId, SavePchOrdRequest savePchOrdRequest) throws Exception {
        try {

            // 로그인 정보 가져오기
            UserMngEntity uEntity = userMngMapper.selectGroupUserInfo(userId);
            uEntity.setTelNo(uEntity.getTelNo().replaceAll("-",""));
            // 전달받은 데이타와 전송발 데이타 세팅 후 저장
            String pchPodrUnqNo = fnGetDealNo(14,"");
            PchOdrBaseInfoEntity pchOrdEntity = new PchOdrBaseInfoEntity();
            pchOrdEntity.setPchPodrUnqNo(pchPodrUnqNo) ;
            pchOrdEntity.setBrandId(savePchOrdRequest.getBrandId());
            pchOrdEntity.setDlvDvsn(savePchOrdRequest.getDlvDvsn());
            pchOrdEntity.setDlvReqDt(savePchOrdRequest.getDlvReqDt().replaceAll("\\.",""));
            pchOrdEntity.setPodrMgrNm(uEntity.getUserNm());
            pchOrdEntity.setPodrDvsn("OD01");
            pchOrdEntity.setPchOdrStCd("PO001");
            pchOrdEntity.setSpplyId(savePchOrdRequest.getSpplyId());
            pchOrdEntity.setPodrMgrId(uEntity.getUserId());
            pchOrdEntity.setPodrMgrTelNo(uEntity.getTelNo());
            //
            if ("".equals(savePchOrdRequest.getStoreId())) {  // 본사납품장소
                pchOrdEntity.setWhsDvsn("W01");
            } else {  // 매장납품장소
                pchOrdEntity.setWhsDvsn("W02");
            }
            pchOrdEntity.setWhsId(savePchOrdRequest.getWhsId());
            pchOrdEntity.setLocation(savePchOrdRequest.getLocation());
            // 본사납품장소이면 아래 데이타는 null값 넘어옴
            pchOrdEntity.setShmtWhsId(savePchOrdRequest.getShmtWhsId());
            pchOrdEntity.setShmtLocation(savePchOrdRequest.getShmtLocation());
            pchOrdEntity.setStoreId(savePchOrdRequest.getStoreId());


            Integer dtlRow = 0 ;
            List<PchOdrDtlPtclEntity> pchOrdDtlList = new ArrayList<PchOdrDtlPtclEntity>();
            List<PchOdrDtlPtclEntity> gridUpdateData = savePchOrdRequest.toCodeEntities(savePchOrdRequest.getGridInsertData());

            List<PchReqBaseInfoEntity> pchReqList = new ArrayList<PchReqBaseInfoEntity>();
            if (gridUpdateData.size() > 0) {
                int poTotAmt = 0 ;
                int poItemCnt = 0 ;
                String  diffSpplyYn = "N" ;
                for (int i = 0 ; i < gridUpdateData.size() ;i++ ) {
                    PchOdrDtlPtclEntity poDtlEntity = gridUpdateData.get(i);
                    PchOdrDtlPtclEntity poSaveDtlEntity = new PchOdrDtlPtclEntity();
                    PchReqBaseInfoEntity pchReqEntity = new PchReqBaseInfoEntity();
                    // 구매요청건에 대한 데이타 가져옴
                    if ("R".equals(savePchOrdRequest.getJobCd())) {   // 구매요청건
                        // 구매요청번호와 항번으로 데이타 가져놈
                        poSaveDtlEntity = pchOrdMapper.selectPoPchDtlSaveInfo(poDtlEntity.getPchReqUnqNo(), poDtlEntity.getPchReqDtlNo());
                        pchReqEntity.setPchReqUnqNo(poDtlEntity.getPchReqUnqNo());
                        pchReqEntity.setPchReqStCd("PR30");
                        pchReqList.add(pchReqEntity);
                    } else if ("P".equals(savePchOrdRequest.getJobCd())) {  // 신규발주건
                        // item id 로 데이타 가져옴  == 단가는 브랜드 단가로 처리함
                        poSaveDtlEntity = pchOrdMapper.selectPoItemDtlSaveInfo(savePchOrdRequest.getBrandId(), poDtlEntity.getItemId(), poDtlEntity.getBrandUnitUnqNo());
                    }

                    if (!pchOrdEntity.getSpplyId().equals(poSaveDtlEntity.getSpplyId())) {
                        diffSpplyYn = "Y";
                    }


                    dtlRow = dtlRow + 10;
                    poSaveDtlEntity.setPchPodrUnqNo(pchPodrUnqNo);
                    String dtlNo = Integer.toString(dtlRow);
                    poSaveDtlEntity.setPchPodrDtlNo(dtlNo);
                    poSaveDtlEntity.setPchReqUnqNo(poDtlEntity.getPchReqUnqNo());
                    poSaveDtlEntity.setPchReqDtlNo(poDtlEntity.getPchReqDtlNo());
                    poSaveDtlEntity.setPodrQty(poDtlEntity.getPodrQty());
                    poSaveDtlEntity.setPodrAmt(poDtlEntity.getPodrQty() * poSaveDtlEntity.getUnitAmt() );
                    poSaveDtlEntity.setCurr("KRW");
                    poSaveDtlEntity.setPodrDtlStCd("POD0");
                    poSaveDtlEntity.setBrandUnitUnqNo(poDtlEntity.getBrandUnitUnqNo());
                    poSaveDtlEntity.setStoreUnitUnqNo(poDtlEntity.getStoreUnitUnqNo());
                    poTotAmt = poTotAmt +  poSaveDtlEntity.getPodrAmt();
                    poItemCnt = poItemCnt + 1;

                    pchOrdDtlList.add(poSaveDtlEntity);
                }

                // 체크로직필요
                if ("W01".equals(pchOrdEntity.getWhsDvsn())) {
                    // 본사납품장소일경우 - 공급사는 하나여야만한다.
                    if("DL02".equals(pchOrdEntity.getDlvDvsn())) {
                        // 본사납품장소이면 배송구분은 공급사이여야 함
                        throw new GlobalException(SystemMessageCode.ERR_DLV001);
                    }
                    // 공급사는 하나여야 함
                    if ("Y".equals(diffSpplyYn)) {
                        // 공급사는 하나여야 합니다.
                        throw new GlobalException(SystemMessageCode.ERR_NEQSPPLY);
                    }
                } else {
                    // 매장납품장소일경우 - 배송구분이 공급사면 - 공급사 하나여야 하고, 본사이면 매장이 하나여야 한다.
                    if ("DL01".equals(pchOrdEntity.getDlvDvsn())) { // 본사배송이면
                        if ("".equals(pchOrdEntity.getStoreId())) {
                            // 매장정보가 없습니다.
                            throw new GlobalException(SystemMessageCode.ERR_NONSTOREID);
                        }

                        //출고창고정보 존재여부 파악
                        if ("".equals(pchOrdEntity.getShmtWhsId()) || "".equals(pchOrdEntity.getShmtLocation())) {
                            throw new GlobalException(SystemMessageCode.ERR_OUTWHS);
                        }

                    } else {  // 공급사배송이면
                        // 공급사는 하나여야 함
                        if ("Y".equals(diffSpplyYn)) {
                            // 공급사는 하나여야 합니다.
                            throw new GlobalException(SystemMessageCode.ERR_NEQSPPLY);
                        }
                    }
                }

                pchOrdEntity.setPodrTotalAmt(poTotAmt);
                pchOrdEntity.setPodrItemQty(poItemCnt);

                pchOrdMapper.insertPchOdrBaseInfo(userId, pchOrdEntity);
                pchOrdMapper.insertPchOdrDtlPtcl(userId, pchOrdDtlList);

                if ("R".equals(savePchOrdRequest.getJobCd())) {   // 구매요청건
                    pchReqMapper.updatePchReqStCd(userId,pchReqList);
                }

                //출고가능수량을 줄여줘야함
                if ("DL01".equals(pchOrdEntity.getDlvDvsn())) { // 본사배송이면
                    //출고창고 값 전달
                    if (pchOrdDtlList.size() > 0) {
                        List<StckMgntBaseInfoEntity> stckList = new ArrayList<StckMgntBaseInfoEntity>();
                        for (int pj = 0 ; pj < pchOrdDtlList.size() ; pj++) {
                            PchOdrDtlPtclEntity poData = pchOrdDtlList.get(pj);
                            StckMgntBaseInfoEntity stckEntity = new StckMgntBaseInfoEntity();
                            stckEntity.setItemId(poData.getItemId());
                            stckEntity.setWaitQty(poData.getPodrQty());
                            stckList.add(stckEntity);
                        }

                        stockMngMapper.updateStckPoUseQty(userId, pchOrdEntity.getBrandId(), pchOrdEntity.getShmtWhsId(), pchOrdEntity.getShmtLocation(), stckList );
                    }
                }
            }

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


    /*
      구매요청 그리드 리스트 조회
     */
    public GridResponse selectPchOdrGridList(String sBrandId, String fromDt, String toDt, String sPchOdrStCd, String sSpplyId, String sWhsId, 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.selectPchOdrGridCnt(sBrandId, fromDt, toDt, sPchOdrStCd,sSpplyId,sWhsId,  sItemNm );
        int gridTotal = fnCalculateGridTotal(gridSize, gridRecords);
        List<PchOdrBaseInfoEntity> entities = pchOrdMapper.selectPchOdrGridList(sBrandId, fromDt, toDt, sPchOdrStCd,sSpplyId,sWhsId,  sItemNm, gridRequest);
        List<Object> gridRows = entities.stream()
                .map(m -> PchOdrSearchListResponse.builder()
                        .viewCd("R")
                        .pchPodrUnqNo(m.getPchPodrUnqNo())
                        .brandId(m.getBrandId() == null ? "" : m.getBrandId())
                        .brandNm(m.getBrandNm() == null ? "" : m.getBrandNm())
                        .pchOdrStCd(m.getPchOdrStCd() == null ? "" : m.getPchOdrStCd())
                        .pchOdrStNm(m.getPchOdrStNm() == null ? "" : m.getPchOdrStNm())
                        .podrDt(m.getPodrDt() == null ? "" : m.getPodrDt())
                        .whsNm(m.getWhsNm() == null ? "" : m.getWhsNm())
                        .locationNm(m.getLocationNm() == null ? "" :  m.getLocationNm())
                        .spplyId(m.getSpplyId() == null ? "" : m.getSpplyId())
                        .spplyNm(m.getSpplyNm() == null ? "" : m.getSpplyNm())
                        .podrTotalAmt(m.getPodrTotalAmt() == null ? 0 : m.getPodrTotalAmt())
                        .podrItemQty(m.getPodrItemQty() == null ? 0 : m.getPodrItemQty())
                        .podrMgrNm(m.getPodrMgrNm() == null ? "" : m.getPodrMgrNm())
                        .shmtWhsNm(m.getShmtWhsNm() == null ? "" : m.getShmtWhsNm())
                        .shmtLocationNm(m.getShmtLocationNm() == null ? "" : m.getShmtLocationNm())
                        .build())
                .collect(Collectors.toList());
        return GridResponse.toDTO(gridPage, gridTotal, gridRecords, gridRows);
    }

    /* 구매발주 정보 */

    public PchOdrInfoResponse selectPchOdrInfo(String  pchReqUnqNo) throws Exception {
        PchOdrBaseInfoEntity entity = pchOrdMapper.selectPchOdrInfo(pchReqUnqNo);
        List<PchOdrDtlPtclEntity> dtlEntity = pchOrdMapper.selectOdrDtlList( pchReqUnqNo);

        return PchOdrInfoResponse.toDTO(entity,dtlEntity);
    }


    /*
      발주 취소처리
     */
    @Transactional
    public void cancelPchOrdDtl(String userId, CancelPchOrdDtlRequest cancelPchOrdDtlRequest) throws Exception {
        try {
            // 품목 삭제 상태처리
            Integer podrAmt = 0 ;
            List<PchOdrDtlPtclEntity> gridUpdateData = cancelPchOrdDtlRequest.toCodeEntities(cancelPchOrdDtlRequest.getGridUpdateData());
            List<StckMgntBaseInfoEntity> stckList = new ArrayList<StckMgntBaseInfoEntity>();
            if (gridUpdateData.size() > 0) {
                pchOrdMapper.updateCancelPodrDtl(userId,  gridUpdateData) ;

                for (int i = 0 ; i < gridUpdateData.size() ; i++) {
                    PchOdrDtlPtclEntity delItem = gridUpdateData.get(i);
                    podrAmt = podrAmt + delItem.getPodrAmt();

                    if ("DL01".equals(cancelPchOrdDtlRequest.getDlvDvsn())) { // 본사배송이면
                        StckMgntBaseInfoEntity stckEntity = new StckMgntBaseInfoEntity();
                        stckEntity.setItemId(delItem.getItemId());
                        stckEntity.setWaitQty(delItem.getPodrQty());
                        stckList.add(stckEntity);
                    }
                }
            }

            //발주취소로 인한 발주 head 상태값 변경처리  pchPodrUnqNo
            String pchOdrStCd = selectOdrDtlStatusList(cancelPchOrdDtlRequest.getPchPodrUnqNo());
            pchOrdMapper.updateChgPodrStCd(userId, pchOdrStCd, cancelPchOrdDtlRequest.getPchPodrUnqNo());

            // 매장 구매요청 발주일경우 사용금액 차감 처리함
            if (!"".equals(cancelPchOrdDtlRequest.getStoreId())) {
                String loanMgntUnqNo = storeBaseInfoMapper.selectStoreLoanMgntUnqNo(cancelPchOrdDtlRequest.getStoreId());

                if (loanMgntUnqNo != null) {
                    loanStateMapper.updateloanMinusPchReqUseAmt(loanMgntUnqNo, cancelPchOrdDtlRequest.getStoreId(), podrAmt);
                }
            }

            //출고가능수량을 복구처리
            if ("DL01".equals(cancelPchOrdDtlRequest.getDlvDvsn())) { // 본사배송이면
                 stockMngMapper.updateStckPoUseQty(userId, cancelPchOrdDtlRequest.getBrandId(), cancelPchOrdDtlRequest.getShmtWhsId(), cancelPchOrdDtlRequest.getShmtLocation(), stckList );
            }

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

    public String  selectOdrDtlStatusList(String  pchReqUnqNo) throws Exception {
        //PCH_ODR_ST_CD
        String pchOdrStCd = "";
        List<PchOdrDtlPtclEntity> dtlEntity = pchOrdMapper.selectOdrDtlStatusList( pchReqUnqNo);

        int pod0 = 0 ;
        int pod1 = 0 ;
        int pod2 = 0 ;
        int pod4 = 0 ;

        for (int i = 0 ; i < dtlEntity.size() ; i++ ) {
            PchOdrDtlPtclEntity entity = dtlEntity.get(i);
            if ( "POD0".equals(entity.getPodrDtlStCd())) {  // 요청
                pod0 = pod0 + entity.getPodrStatusCnt() ;
            } else if ( "POD1".equals(entity.getPodrDtlStCd()) ||  "POD3".equals(entity.getPodrDtlStCd())) {  // 접수 ,출하
                pod1 = pod1 + entity.getPodrStatusCnt() ;
            } else if ( "POD2".equals(entity.getPodrDtlStCd())) {  //발주취소
                pod2 = pod2 + entity.getPodrStatusCnt() ;
            } else if ( "POD4".equals(entity.getPodrDtlStCd())) {  //입고완료
                pod4 = pod4 + entity.getPodrStatusCnt() ;
            }
        }

        if (pod0 > 0 ) {
            pchOdrStCd = "PO20";  //요청
        } else if ( pod0 == 0 && pod1 == 0 &&  pod4 == 0 ) {
            pchOdrStCd = "PO99";  // 취소
        } else {
            pchOdrStCd = "PO30";  // 접수
        }

        return pchOdrStCd;
    }

}
