package com.oqpo.api.service.inoutmng;


import com.oqpo.api.entity.inoutmng.DeliDtlMgntEntity;
import com.oqpo.api.entity.inoutmng.DeliInfoMgntEntity;
import com.oqpo.api.entity.inoutmng.ShmtOdrBaseEntity;
import com.oqpo.api.entity.inoutmng.ShmtOdrDtlEntity;
import com.oqpo.api.entity.pomng.PchOdrBaseInfoEntity;
import com.oqpo.api.entity.pomng.PchOdrDtlPtclEntity;
import com.oqpo.api.entity.stockmng.StckMgntBaseInfoEntity;
import com.oqpo.api.entity.stockmng.StckMgntDtlHistEntity;
import com.oqpo.api.enums.ChgDvsn;
import com.oqpo.api.enums.InOutCd;
import com.oqpo.api.enums.SystemMessageCode;
import com.oqpo.api.exception.GlobalException;
import com.oqpo.api.mapper.CommonMapper;
import com.oqpo.api.mapper.inoutmng.ShmtOdrMapper;
import com.oqpo.api.mapper.pomng.PchOrdMapper;
import com.oqpo.api.mapper.stockmng.StockMngMapper;
import com.oqpo.api.service.CommonService;
import com.oqpo.api.service.pomng.PchOrdService;
import com.oqpo.api.web.dto.request.GridRequest;
import com.oqpo.api.web.dto.request.inoutmng.InstShmtOdrRequest;
import com.oqpo.api.web.dto.response.GridResponse;
import com.oqpo.api.web.dto.response.inoutmng.ShmtOdrSearchListResponse;
import com.oqpo.api.web.dto.response.inoutmng.ShmtOutSearchListResponse;
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 ShmtOdrService extends CommonService {
    @Autowired
    private ShmtOdrMapper shmtOdrMapper;

    @Autowired
    private StockMngMapper stockMngMapper;

    @Autowired
    private PchOrdMapper pchOrdMapper;

    @Autowired
    private PchOrdService pchOrdService;

    @Autowired
    private CommonMapper commonMapper;

    /*
    @Autowired
    private UserMngMapper userMngMapper;

    @Autowired
    private StockMngMapper stockMngMapper;

    @Autowired
    private PchReqMapper pchReqMapper;

    @Autowired
    private StoreBaseInfoMapper storeBaseInfoMapper;

    @Autowired
    private LoanStateMapper loanStateMapper;

*/
    /*
      출하 대상 그리드 리스트 조회
     */
    public GridResponse selectShmtTargetOdrGridList(String sBrandId, String fromDt, String toDt, String sShmtWhsId, 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 = shmtOdrMapper.selectShmtTargetOdrGridCnt( sBrandId, fromDt, toDt, sShmtWhsId, sWhsId, sItemNm );
        int gridTotal = fnCalculateGridTotal(gridSize, gridRecords);
        List<PchOdrBaseInfoEntity> entities = shmtOdrMapper.selectShmtTargetOdrGridList(sBrandId, fromDt, toDt, sShmtWhsId, sWhsId, sItemNm, gridRequest);
        List<Object> gridRows = entities.stream()
                .map(m -> ShmtOdrSearchListResponse.builder()
                        .viewCd("R")
                        .brandId(m.getBrandId() == null ? "" : m.getBrandId())
                        .brandNm(m.getBrandNm() == null ? "" : m.getBrandNm())
                        .pchPodrUnqNo(m.getPchPodrUnqNo() == null ? "" : m.getPchPodrUnqNo())
                        .pchPodrDtlNo(m.getPchOdrDtlInfo() == null ? "" : m.getPchOdrDtlInfo().getPchPodrDtlNo() == null ? "" :  m.getPchOdrDtlInfo().getPchPodrDtlNo() )
                        .itemId(m.getPchOdrDtlInfo() == null ? "" : m.getPchOdrDtlInfo().getItemId() == null  ? "" : m.getPchOdrDtlInfo().getItemId())
                        .itemNm(m.getPchOdrDtlInfo() == null ? "" : m.getPchOdrDtlInfo().getItemNm() == null ? "" : m.getPchOdrDtlInfo().getItemNm())
                        .whsId(m.getWhsId() == null ? "" : m.getWhsId())
                        .whsNm(m.getWhsNm() == null ? "" : m.getWhsNm() + " - " + m.getLocationNm())
                        .location(m.getLocation() == null ? "" : m.getLocation())
                        .unitAmt(m.getPchOdrDtlInfo() == null ? 0 : m.getPchOdrDtlInfo().getUnitAmt() == null ? 0 : m.getPchOdrDtlInfo().getUnitAmt())
                        .podrQty(m.getPchOdrDtlInfo() == null ? 0 : m.getPchOdrDtlInfo().getPodrQty() == null ? 0 : m.getPchOdrDtlInfo().getPodrQty())
                        .shmtQty(m.getPchOdrDtlInfo() == null ? 0 : m.getPchOdrDtlInfo().getShmtQty() == null ? 0 : m.getPchOdrDtlInfo().getShmtQty())
                        .stckQty(m.getPchOdrDtlInfo() == null ? 0 : m.getPchOdrDtlInfo().getStckQty() == null ? 0 : m.getPchOdrDtlInfo().getStckQty())
                        .expryYn(m.getPchOdrDtlInfo() == null ? "" : m.getPchOdrDtlInfo().getExpryYn() == null ? "" :  m.getPchOdrDtlInfo().getExpryYn() )
                        .expryPeriod(m.getPchOdrDtlInfo() == null ? 0 : m.getPchOdrDtlInfo().getExpryPeriod() == null ? 0 : m.getPchOdrDtlInfo().getExpryPeriod())
                        .expryDate(m.getPchOdrDtlInfo() == null ? "" : m.getPchOdrDtlInfo().getExpryDate() == null ? "" : m.getPchOdrDtlInfo().getExpryDate())
                        .podrAmt(m.getPchOdrDtlInfo() == null ? 0 : m.getPchOdrDtlInfo().getPodrAmt() == null ? 0 : m.getPchOdrDtlInfo().getPodrAmt())
                        .dlvReqDt(m.getDlvReqDt() == null ? "" : m.getDlvReqDt())
                        .shmtWhsId(m.getShmtWhsId() == null ? "" : m.getShmtWhsId())
                        .shmtLocation(m.getShmtLocation() == null ? "" : m.getShmtLocation())
                        .shmtWhsNm(m.getShmtWhsNm() == null ? "" : m.getShmtWhsNm() + " - " + m.getShmtLocationNm())
                        .build())
                .collect(Collectors.toList());
        return GridResponse.toDTO(gridPage, gridTotal, gridRecords, gridRows);
    }

    /*
      출하지시 저장
     */
    @Transactional
    public void instShmtOdr(String userId, InstShmtOdrRequest instShmtOdrRequest) throws Exception {
        try {
                // 출하창고 + 납품장소 동일여부 체크
                // 출하창고의 재고 와 출하수량 비교처리
                // 발주수량은 출하수량보다 크거나 같아야함
                // 유통기한 품목에 대해서는 유통기한일자 기입 필수

                // 출하 헤더 생성
                // 출하 상세 생성
                // 납품서 헤더 생성
                // 납품서 상세 생성성
            List<PchOdrDtlPtclEntity> gridInsertData = instShmtOdrRequest.toCodeEntities(instShmtOdrRequest.getGridInsertData());
            List<PchOdrBaseInfoEntity> jobList = shmtOdrMapper.selectShmtJobDataList(instShmtOdrRequest.getBrandId(), gridInsertData) ;
            List<StckMgntBaseInfoEntity> stockList = new ArrayList<StckMgntBaseInfoEntity>();
            String whsId = "";
            String location = "";
            String shmtWhsId = "";
            String shmtLocation = "";
            int itemQty = 0 ;
            int shmtTotalAmt = 0 ;
            String expryDate = "";
            int shmtQty = 0 ;
            String shmtReqUnqNo = "";
            String dlvSttmtUnqNo = "";


            ShmtOdrBaseEntity shmtBaseEntity = new ShmtOdrBaseEntity();
            List<ShmtOdrDtlEntity> shmtDtlList = new ArrayList<ShmtOdrDtlEntity>() ;

            DeliInfoMgntEntity deliBaseEntity = new DeliInfoMgntEntity();
            List<DeliDtlMgntEntity> deliDtlList = new ArrayList<DeliDtlMgntEntity>() ;

            for (int i = 0 ; i < jobList.size() ; i++) {
                PchOdrBaseInfoEntity entity = jobList.get(i);

                for (int j = 0 ; j < gridInsertData.size() ; j++) {
                    PchOdrDtlPtclEntity reqEntity = gridInsertData.get(j);

                    if (entity.getPchPodrUnqNo().equals(reqEntity.getPchPodrUnqNo())  &&  entity.getPchOdrDtlInfo().getPchPodrDtlNo().equals(reqEntity.getPchPodrDtlNo()))
                    {
                        if (reqEntity.getShmtQty() > entity.getPchOdrDtlInfo().getPodrQty()) {
                            // 발주수량보다 출고수량이 많을수 없습니다.
                            throw new GlobalException(SystemMessageCode.ERR_POSHNONQTY);
                        }

                        if ("Y".equals(entity.getPchOdrDtlInfo().getExpryYn())) {
                            if (reqEntity.getExpryDate() == null || "".equals(reqEntity.getExpryDate())) {
                                // 유통기한을 입력해주세요!
                                throw new GlobalException(SystemMessageCode.ERR_NONEXPRY);
                            }
                        }
                        expryDate = reqEntity.getExpryDate().replaceAll("\\.","");
                        shmtQty = reqEntity.getShmtQty();

                        break;
                    }
                }

                if (shmtWhsId.equals(entity.getShmtWhsId()) && shmtLocation.equals(entity.getShmtLocation()) && whsId.equals(entity.getWhsId()) &&  location.equals(entity.getLocation())) {
                    // 추가 작업
                    itemQty = itemQty + 1 ;
                    shmtTotalAmt = shmtTotalAmt + (entity.getPchOdrDtlInfo().getUnitAmt() * shmtQty);
                    shmtBaseEntity.setItemQty(itemQty);
                    shmtBaseEntity.setShmtTotalAmt(shmtTotalAmt);
                    deliBaseEntity.setDlvAmt(shmtTotalAmt);

                    ShmtOdrDtlEntity inaddDtlEntity = new ShmtOdrDtlEntity();
                    inaddDtlEntity.setShmtReqUnqNo(shmtReqUnqNo);
                    int dtlNo = itemQty * 10 ;
                    inaddDtlEntity.setShmtReqDtlNo( Integer.toString(dtlNo));
                    inaddDtlEntity.setItemId(entity.getPchOdrDtlInfo().getItemId());
                    inaddDtlEntity.setItemNm(entity.getPchOdrDtlInfo().getItemNm());
                    inaddDtlEntity.setUnitAmt(entity.getPchOdrDtlInfo().getUnitAmt());
                    inaddDtlEntity.setUnit(entity.getPchOdrDtlInfo().getUnit());
                    inaddDtlEntity.setPodrQty(entity.getPchOdrDtlInfo().getPodrQty());
                    inaddDtlEntity.setPodrAmt(entity.getPchOdrDtlInfo().getPodrAmt());
                    inaddDtlEntity.setShmtQty(shmtQty);
                    inaddDtlEntity.setShmtAmt(shmtQty * entity.getPchOdrDtlInfo().getUnitAmt());
                    inaddDtlEntity.setExpryDate(expryDate);
                    inaddDtlEntity.setPchPodrUnqNo(entity.getPchPodrUnqNo());
                    inaddDtlEntity.setPchPodrDtlNo(entity.getPchOdrDtlInfo().getPchPodrDtlNo());
                    inaddDtlEntity.setPchReqUnqNo(entity.getPchOdrDtlInfo().getPchReqUnqNo());
                    inaddDtlEntity.setPchReqDtlNo(entity.getPchOdrDtlInfo().getPchReqDtlNo());

                    shmtDtlList.add(inaddDtlEntity);

                    //재고 수량정보 기입
                    StckMgntBaseInfoEntity stckEntity = new StckMgntBaseInfoEntity();
                    /*
                    String dupYn = "N";
                    for (int ski = 0 ; ski < stockList.size() ; ski++) {
                        StckMgntBaseInfoEntity tmpEntity = stockList.get(ski);
                        if (entity.getBrandId().equals(tmpEntity.getBrandId()) && entity.getShmtWhsId().equals(tmpEntity.getWhsId())
                                 && entity.getShmtLocation().equals(tmpEntity.getLocation()) && entity.getPchOdrDtlInfo().getItemId().equals(tmpEntity.getItemId())) {
                            int tmpStckQty = tmpEntity.getStckQty() ;
                            stockList.get(ski).setStckQty(tmpStckQty + shmtQty);
                            dupYn = "Y";
                            System.out.println("for============================" + Integer.toString(ski) + stockList.get(ski).getStckQty());
                            break;
                        }
                    }
                    if ("N".equals(dupYn)) {
                    */
                        stckEntity.setBrandId(entity.getBrandId());
                        stckEntity.setWhsId(entity.getShmtWhsId());
                        stckEntity.setLocation(entity.getShmtLocation());
                        stckEntity.setItemId(entity.getPchOdrDtlInfo().getItemId());
                        stckEntity.setStckQty(shmtQty);
                        stckEntity.setRelationNo(shmtReqUnqNo);
                        stockList.add(stckEntity);
                  //  }

                    //납품서 상세 생성
                    DeliDtlMgntEntity inaddDeliDtlEntity = new DeliDtlMgntEntity();
                    inaddDeliDtlEntity.setDlvSttmtUnqNo(dlvSttmtUnqNo);
                    inaddDeliDtlEntity.setDlvSttmtDtlNo(Integer.toString(dtlNo));
                    inaddDeliDtlEntity.setPchPodrUnqNo(entity.getPchPodrUnqNo());
                    inaddDeliDtlEntity.setPchPodrDtlNo(entity.getPchOdrDtlInfo().getPchPodrDtlNo());
                    inaddDeliDtlEntity.setPchReqUnqNo(entity.getPchOdrDtlInfo().getPchReqUnqNo());
                    inaddDeliDtlEntity.setPchReqDtlNo(entity.getPchOdrDtlInfo().getPchReqDtlNo());
                    inaddDeliDtlEntity.setItemId(entity.getPchOdrDtlInfo().getItemId());
                    inaddDeliDtlEntity.setItemNm(entity.getPchOdrDtlInfo().getItemNm());
                    inaddDeliDtlEntity.setUnit(entity.getPchOdrDtlInfo().getUnit());
                    inaddDeliDtlEntity.setUnitAmt(entity.getPchOdrDtlInfo().getUnitAmt());
                    inaddDeliDtlEntity.setPodrQty(entity.getPchOdrDtlInfo().getPodrQty());
                    inaddDeliDtlEntity.setDlvQty(shmtQty);
                    inaddDeliDtlEntity.setPodrAmt(entity.getPchOdrDtlInfo().getPodrAmt());
                    inaddDeliDtlEntity.setDlvAmt(shmtQty * entity.getPchOdrDtlInfo().getUnitAmt());
                    inaddDeliDtlEntity.setExpryDate(expryDate);

                    deliDtlList.add(inaddDeliDtlEntity);


                } else {
                    // 신규로 출하건 생성함  //select fn_get_dealno(16, '') as col_cmd_unq_no
                    if (shmtDtlList.size() > 0) {
                        shmtOdrMapper.insertShmtOdrBase(userId,shmtBaseEntity );
                        shmtOdrMapper.insertShmtOdrDtl(userId, shmtDtlList) ;

                        shmtOdrMapper.insertDeliInfoMngt(userId,deliBaseEntity );
                        shmtOdrMapper.insertDeliDtlPtcl(userId, deliDtlList) ;
                        itemQty = 0 ;
                        shmtTotalAmt = 0 ;
                    }
                    itemQty = 1 ;
                    shmtTotalAmt = entity.getPchOdrDtlInfo().getUnitAmt() * shmtQty;

                    whsId = entity.getWhsId();
                    location = entity.getLocation();
                    shmtWhsId = entity.getShmtWhsId();
                    shmtLocation = entity.getShmtLocation();

                    shmtReqUnqNo = fnGetDealNo(16,"");  // 출하지시번호
                    dlvSttmtUnqNo = fnGetDealNo(15,""); // 납품서번호

                    // 출하지시
                    shmtBaseEntity = new ShmtOdrBaseEntity();
                    shmtDtlList = new ArrayList<ShmtOdrDtlEntity>() ;
                    ShmtOdrDtlEntity inDtlEntity = new ShmtOdrDtlEntity();

                    //납품서정보
                    deliBaseEntity = new DeliInfoMgntEntity();
                    deliDtlList = new ArrayList<DeliDtlMgntEntity>() ;
                    DeliDtlMgntEntity deliDtlEntity = new DeliDtlMgntEntity();

                    shmtBaseEntity.setShmtReqUnqNo(shmtReqUnqNo);
                    shmtBaseEntity.setShmtReqStCd("SHM1");
                    shmtBaseEntity.setShmtWhsId(entity.getShmtWhsId());
                    shmtBaseEntity.setShmtLocation(entity.getShmtLocation());
                    shmtBaseEntity.setWhsDvsn("W01");
                    shmtBaseEntity.setBrandId(entity.getBrandId());
                    shmtBaseEntity.setStoreId(entity.getStoreId());
                    shmtBaseEntity.setPodrDvsn("OD01");
                    shmtBaseEntity.setItemQty(itemQty);
                    shmtBaseEntity.setShmtTotalAmt(shmtTotalAmt);
                    shmtBaseEntity.setPodrMgrNm(entity.getPodrMgrNm());
                    shmtBaseEntity.setDlvReqDt(entity.getDlvReqDt().replaceAll("\\.",""));
                    shmtBaseEntity.setWhsId(entity.getWhsId());
                    shmtBaseEntity.setLocation(entity.getLocation());

                    //납품서 데이타 생성
                    deliBaseEntity.setDlvSttmtUnqNo(dlvSttmtUnqNo);
                    deliBaseEntity.setSpplyId(null);
                    deliBaseEntity.setSpplyNm(null);
                    //deliBaseEntity.setDlvRegDt();
                    deliBaseEntity.setDlvAmt(shmtTotalAmt);
                    deliBaseEntity.setDlvMgrNm(instShmtOdrRequest.getDlvMgrNm());
                    deliBaseEntity.setDlvMgrTelNo(instShmtOdrRequest.getDlvMgrTelNo().replaceAll("-",""));
                    deliBaseEntity.setDlvMgrEmal(null);
                    deliBaseEntity.setDlvMgrMblNo(null);
                    deliBaseEntity.setVndrTelNo(entity.getDeliTelNo().replaceAll("-",""));
                    deliBaseEntity.setDlvStCd("DLV0");
                    deliBaseEntity.setPodrRegDt(entity.getPodrDt());
                    deliBaseEntity.setDlvReqDt(entity.getDlvReqDt().replaceAll("\\.",""));
                    deliBaseEntity.setDlvSchDt(instShmtOdrRequest.getDlvSchDt().replaceAll("\\.",""));
                    deliBaseEntity.setDlvCmpltDt(null);
                    deliBaseEntity.setWhsId(entity.getWhsId());
                    deliBaseEntity.setLocation(entity.getLocation());
                    deliBaseEntity.setWhsDvsn("W01");
                    deliBaseEntity.setBrandId(instShmtOdrRequest.getBrandId());

                    //출하지시 상세 생성
                    ShmtOdrDtlEntity inaddDtlEntity = new ShmtOdrDtlEntity();
                    inaddDtlEntity.setShmtReqUnqNo(shmtReqUnqNo);
                    inaddDtlEntity.setShmtReqDtlNo("10");
                    inaddDtlEntity.setItemId(entity.getPchOdrDtlInfo().getItemId());
                    inaddDtlEntity.setItemNm(entity.getPchOdrDtlInfo().getItemNm());
                    inaddDtlEntity.setUnitAmt(entity.getPchOdrDtlInfo().getUnitAmt());
                    inaddDtlEntity.setUnit(entity.getPchOdrDtlInfo().getUnit());
                    inaddDtlEntity.setPodrQty(entity.getPchOdrDtlInfo().getPodrQty());
                    inaddDtlEntity.setPodrAmt(entity.getPchOdrDtlInfo().getPodrAmt());
                    inaddDtlEntity.setShmtQty(shmtQty);
                    inaddDtlEntity.setShmtAmt(shmtQty * entity.getPchOdrDtlInfo().getUnitAmt());
                    inaddDtlEntity.setExpryDate(expryDate);
                    inaddDtlEntity.setPchPodrUnqNo(entity.getPchPodrUnqNo());
                    inaddDtlEntity.setPchPodrDtlNo(entity.getPchOdrDtlInfo().getPchPodrDtlNo());
                    inaddDtlEntity.setPchReqUnqNo(entity.getPchOdrDtlInfo().getPchReqUnqNo());
                    inaddDtlEntity.setPchReqDtlNo(entity.getPchOdrDtlInfo().getPchReqDtlNo());

                    shmtDtlList.add(inaddDtlEntity);

                    StckMgntBaseInfoEntity stckEntity = new StckMgntBaseInfoEntity();
                    stckEntity.setBrandId(entity.getBrandId());
                    stckEntity.setWhsId(entity.getShmtWhsId());
                    stckEntity.setLocation(entity.getShmtLocation());
                    stckEntity.setItemId(entity.getPchOdrDtlInfo().getItemId());
                    stckEntity.setStckQty(shmtQty);
                    stckEntity.setRelationNo(shmtReqUnqNo);
                    stockList.add(stckEntity);

                    //납품서 상세 생성
                    DeliDtlMgntEntity inaddDeliDtlEntity = new DeliDtlMgntEntity();
                    inaddDeliDtlEntity.setDlvSttmtUnqNo(dlvSttmtUnqNo);
                    inaddDeliDtlEntity.setDlvSttmtDtlNo("10");
                    inaddDeliDtlEntity.setPchPodrUnqNo(entity.getPchPodrUnqNo());
                    inaddDeliDtlEntity.setPchPodrDtlNo(entity.getPchOdrDtlInfo().getPchPodrDtlNo());
                    inaddDeliDtlEntity.setPchReqUnqNo(entity.getPchOdrDtlInfo().getPchReqUnqNo());
                    inaddDeliDtlEntity.setPchReqDtlNo(entity.getPchOdrDtlInfo().getPchReqDtlNo());
                    inaddDeliDtlEntity.setItemId(entity.getPchOdrDtlInfo().getItemId());
                    inaddDeliDtlEntity.setItemNm(entity.getPchOdrDtlInfo().getItemNm());
                    inaddDeliDtlEntity.setUnit(entity.getPchOdrDtlInfo().getUnit());
                    inaddDeliDtlEntity.setUnitAmt(entity.getPchOdrDtlInfo().getUnitAmt());
                    inaddDeliDtlEntity.setPodrQty(entity.getPchOdrDtlInfo().getPodrQty());
                    inaddDeliDtlEntity.setDlvQty(shmtQty);
                    inaddDeliDtlEntity.setPodrAmt(entity.getPchOdrDtlInfo().getPodrAmt());
                    inaddDeliDtlEntity.setDlvAmt(shmtQty * entity.getPchOdrDtlInfo().getUnitAmt());
                    inaddDeliDtlEntity.setExpryDate(expryDate);

                    deliDtlList.add(inaddDeliDtlEntity);

                }

                // 마지막 부분일 경우 
                if (i == jobList.size()-1) {
                    if (shmtDtlList.size() > 0) {
                        shmtOdrMapper.insertShmtOdrBase(userId,shmtBaseEntity );
                        shmtOdrMapper.insertShmtOdrDtl(userId, shmtDtlList) ;
                        shmtOdrMapper.insertDeliInfoMngt(userId,deliBaseEntity );
                        shmtOdrMapper.insertDeliDtlPtcl(userId, deliDtlList) ;
                    }
                }

                System.out.println("============================" + stockList.size());

                System.out.println("============================" + "end");

                // 재고수량 변동 및 안전비율계산(없애기로함) 처리후 저장함함
                stockMngMapper.updateMinStockQty(userId,stockList );
                //재고 이력 테이블에 데이타 생성  insertMultiStckMgntDtlHist
                List<StckMgntDtlHistEntity> stockHistList = new ArrayList<StckMgntDtlHistEntity>();
                for ( int m = 0 ; m < stockList.size() ; m++) {
                    StckMgntBaseInfoEntity baseEntity = stockList.get(m);
                    StckMgntDtlHistEntity sourceHist = new StckMgntDtlHistEntity();
                    //String stckMgntDtlNo = fnGetDealNo(32,"");
                    String stckMgntDtlNo =  commonMapper.selectDealNo(32, "");
                    //String stckMgntDtlNo1 =  commonMapper.selectDealNo(33, "");

                    sourceHist.setStckMgntDtlNo(stckMgntDtlNo); // 재고관리상세번호
                   // System.out.println("seqno =========>" +sourceHist.getStckMgntDtlNo() + "===" + stckMgntDtlNo + "==" + stckMgntDtlNo1);
                    sourceHist.setBrandId(baseEntity.getBrandId());
                    sourceHist.setWhsId(baseEntity.getWhsId());
                    sourceHist.setLocation(baseEntity.getLocation());
                    sourceHist.setItemId(baseEntity.getItemId());
                    sourceHist.setItemNm(baseEntity.getItemNm());
                    sourceHist.setInoutCd(InOutCd.OUT.getCd()); // 출고
                    sourceHist.setInoutQty(baseEntity.getStckQty());
                    sourceHist.setChgDvsn(ChgDvsn.PURCHASE_OUT.getCd()); // 구매출고
                    sourceHist.setRelationNo(baseEntity.getRelationNo());
                    stockHistList.add(sourceHist);
                }
                stockMngMapper.insertMultiStckMgntDtlHist(userId, stockHistList);

                // 발주상태 변경처리
                // 1. 발주상세정보 상태 없데이트 한후  pchOrdMapper


                for (int poi = 0 ; poi < gridInsertData.size() ; poi++) {
                    gridInsertData.get(poi).setPodrDtlStCd("POD3");
                }
                pchOrdMapper.updateChangeStPodrDtl(userId,gridInsertData );

                // 발주 헤더 상태 처리  updateChgMultiPodrStCd
                String pchPodrUnqNo = "";
                for (int k = 0 ; k < gridInsertData.size() ; k++) {
                    if (!pchPodrUnqNo.equals(gridInsertData.get(k).getPchPodrUnqNo())) {
                        pchPodrUnqNo = gridInsertData.get(k).getPchPodrUnqNo();
                        String pchOdrStCd = pchOrdService.selectOdrDtlStatusList(pchPodrUnqNo);
                        pchOrdMapper.updateChgPodrStCd(userId, pchOdrStCd, pchPodrUnqNo );
                    }
                }
            }


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

    /* 출하현황 */
    public GridResponse selectShmtSearchGridList(String sBrandId, String fromDt, String toDt, String sShmtWhsId, String sShmtReqStCd,  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 = shmtOdrMapper.selectShmtSearchGridCnt( sBrandId, fromDt, toDt, sShmtWhsId, sShmtReqStCd, sWhsId, sItemNm );
        int gridTotal = fnCalculateGridTotal(gridSize, gridRecords);
        List<ShmtOdrBaseEntity> entities = shmtOdrMapper.selectShmtSearchGridList(sBrandId, fromDt, toDt, sShmtWhsId, sShmtReqStCd, sWhsId, sItemNm, gridRequest);
        List<Object> gridRows = entities.stream()
                .map(m -> ShmtOutSearchListResponse.builder()
                        .viewCd("R")
                        .shmtReqUnqNo(m.getShmtReqUnqNo() == null ? "" : m.getShmtReqUnqNo())
                        .shmtReqDtlNo(m.getShmtOdrDtlInfo() == null ? "" : m.getShmtOdrDtlInfo().getShmtReqDtlNo() == null ? "" : m.getShmtOdrDtlInfo().getShmtReqDtlNo())
                        .brandId(m.getBrandId() == null ? "" : m.getBrandId())
                        .brandNm(m.getBrandNm() == null ? "" : m.getBrandNm())
                        .pchPodrUnqNo(m.getShmtOdrDtlInfo() == null ? "" : m.getShmtOdrDtlInfo().getPchPodrUnqNo() == null ? "" : m.getShmtOdrDtlInfo().getPchPodrUnqNo() )
                        .pchPodrDtlNo(m.getShmtOdrDtlInfo() == null ? "" : m.getShmtOdrDtlInfo().getPchPodrDtlNo() == null ? "" : m.getShmtOdrDtlInfo().getPchPodrDtlNo() )
                        .shmtReqStCd(m.getShmtReqStCd() == null ? "" : m.getShmtReqStCd())
                        .shmtReqStNm(m.getShmtReqStNm() == null ? "" : m.getShmtReqStNm())
                        .itemId(m.getShmtOdrDtlInfo() == null ? "" :m.getShmtOdrDtlInfo().getItemId() == null ? "" : m.getShmtOdrDtlInfo().getItemId())
                        .itemNm(m.getShmtOdrDtlInfo() == null ? "" :m.getShmtOdrDtlInfo().getItemNm() == null ? "" : m.getShmtOdrDtlInfo().getItemNm())
                        .whsId(m.getWhsId() == null ? "" : m.getWhsId())
                        .whsNm(m.getWhsNm() == null ? "" : m.getWhsNm() + " - " + m.getLocationNm())
                        .location(m.getLocation() == null ? "" : m.getLocation())
                        .shmtQty(m.getShmtOdrDtlInfo() == null ? 0 : m.getShmtOdrDtlInfo().getShmtQty() == null ? 0 : m.getShmtOdrDtlInfo().getShmtQty() )
                        .shmtAmt(m.getShmtOdrDtlInfo() == null ? 0 : m.getShmtOdrDtlInfo().getShmtAmt() == null ? 0 : m.getShmtOdrDtlInfo().getShmtAmt() )
                        .whsQty(m.getWhsProcInfo() == null ? 0 : m.getWhsProcInfo().getWhsQty() == null ? 0 : m.getWhsProcInfo().getWhsQty() )
                        .whsAmt(m.getWhsProcInfo() == null ? 0 : m.getWhsProcInfo().getWhsAmt() == null ? 0 : m.getWhsProcInfo().getWhsAmt())
                        .whsDt(m.getWhsProcInfo() == null ? "" : m.getWhsProcInfo().getWhsDt() == null ? "" : m.getWhsProcInfo().getWhsDt() )
                        .whsCnfmNm(m.getWhsProcInfo() == null ? "" : m.getWhsProcInfo().getWhsCnfmNm() == null ? "" : m.getWhsProcInfo().getWhsCnfmNm() )
                        .build())
                .collect(Collectors.toList());
        return GridResponse.toDTO(gridPage, gridTotal, gridRecords, gridRows);
    }
}
