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.loanmng.LoanMgntBaseInfoEntity;
import com.oqpo.api.entity.loanmng.LoanMgntDtlHstEntity;
import com.oqpo.api.entity.oper.FileEntity;
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.settmng.StlMgntBaseInfoEntity;
import com.oqpo.api.entity.settmng.StlMgntDtlPtclEntity;
import com.oqpo.api.entity.stinfo.BrandEntity;
import com.oqpo.api.entity.stinfo.SpplyEntity;
import com.oqpo.api.entity.stinfo.StoreBaseInfoEntity;
import com.oqpo.api.entity.stockmng.StckMgntBaseInfoEntity;
import com.oqpo.api.entity.stockmng.StckMgntDtlHistEntity;
import com.oqpo.api.entity.stockmng.WhsProcInfoPtclEntity;
import com.oqpo.api.enums.*;
import com.oqpo.api.exception.GlobalException;
import com.oqpo.api.mapper.FileMapper;
import com.oqpo.api.mapper.inoutmng.ShmtOdrMapper;
import com.oqpo.api.mapper.loanmng.DsptMngMapper;
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.stinfo.BrandMapper;
import com.oqpo.api.mapper.stinfo.StoreBaseInfoMapper;
import com.oqpo.api.mapper.stinfo.SupplyMapper;
import com.oqpo.api.mapper.stockmng.StockMngMapper;
import com.oqpo.api.mapper.sttlmng.SttlReqMapper;
import com.oqpo.api.service.CommonService;
import com.oqpo.api.service.pomng.PchOrdService;
import com.oqpo.api.util.DateUtil;
import com.oqpo.api.web.dto.request.GridRequest;
import com.oqpo.api.web.dto.request.inoutmng.InstShmtOdrRequest;
import com.oqpo.api.web.dto.request.inoutmng.SaveSpplyDlvRequest;
import com.oqpo.api.web.dto.request.inoutmng.SaveWarehouseProcRequest;
import com.oqpo.api.web.dto.response.GridResponse;
import com.oqpo.api.web.dto.response.inoutmng.*;
import com.oqpo.api.web.dto.response.pomng.pchOrd.SpplyPoOdrSearchListResponse;
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 BrandMapper brandMapper;

    @Autowired
    private SupplyMapper supplyMapper;

    @Autowired
    private StoreBaseInfoMapper storeBaseInfoMapper;

    @Autowired
    private LoanStateMapper loanStateMapper;

    @Autowired
    private FileMapper fileMapper;

    @Autowired
    private UserMngMapper userMngMapper;

    @Autowired
    private SttlReqMapper sttlReqMapper;

    @Autowired
    private DsptMngMapper dsptMngMapper;



    /*
      출하 대상 그리드 리스트 조회
     */
    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 {
            // 출하창고 + 납품장소 동일여부 체크
            // 출하창고의 재고 와 출하수량 비교처리
            // 발주수량은 출하수량보다 크거나 같아야함
            // 유통기한 품목에 대해서는 유통기한일자 기입 필수

            // 출하 헤더 생성loanList
            // 출하 상세 생성
            // 납품서 헤더 생성
            // 납품서 상세 생성성
            List<PchOdrDtlPtclEntity> gridInsertData = instShmtOdrRequest.toCodeEntities(instShmtOdrRequest.getGridInsertData());
            List<PchOdrBaseInfoEntity> jobList = shmtOdrMapper.selectShmtJobDataList(instShmtOdrRequest.getBrandId(), gridInsertData);
            List<StckMgntBaseInfoEntity> stockList = new ArrayList<StckMgntBaseInfoEntity>();

            //여신관련하여 출하지시시 납품수량이 발주수량보다 적을 경우 사용금액을 차액만큼 원복처리를 위한 데이타
            List<LoanMgntBaseInfoEntity> loanList = new ArrayList<LoanMgntBaseInfoEntity>();

            String whsId = "";
            String location = "";
            String shmtWhsId = "";
            String shmtLocation = "";
            int itemQty = 0;
            long 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())) {
                                // 유통기한을 입력해주세요!instShmtOdrRequest
                                throw new GlobalException(SystemMessageCode.ERR_NONEXPRY);
                            }
                        }

                        if (reqEntity.getShmtQty() < entity.getPchOdrDtlInfo().getPodrQty()) {
                            // 출고수량보다 발주수량클경우 구매금액을 차감 처리. selectStoreLoanMgntUnqNo
                            String loanMgntUnqNo = storeBaseInfoMapper.selectStoreLoanMgntUnqNo(entity.getStoreId());

                            if (loanList.size() > 0) {
                                String exchk = "N";
                                for (int la = 0 ; la < loanList.size() ; la++ ) {
                                    if (loanMgntUnqNo.equals(loanList.get(la).getLoanMgntUnqNo())) {
                                        long sumAmt = loanList.get(la).getUseAmtTotal();
                                        sumAmt = sumAmt + ((entity.getPchOdrDtlInfo().getPodrQty() - reqEntity.getShmtQty()) * entity.getPchOdrDtlInfo().getUnitAmt());
                                        loanList.get(la).setUseAmtTotal(sumAmt);
                                        exchk = "Y";
                                        break;
                                    }
                                }
                                if ("N".equals(exchk)) {
                                    LoanMgntBaseInfoEntity loanEntity = new LoanMgntBaseInfoEntity();
                                    loanEntity.setLoanMgntUnqNo(loanMgntUnqNo);
                                    loanEntity.setStoreId(entity.getStoreId());
                                    loanEntity.setUseAmtTotal( Long.valueOf ((entity.getPchOdrDtlInfo().getPodrQty() - reqEntity.getShmtQty()) * entity.getPchOdrDtlInfo().getUnitAmt()));
                                    loanList.add(loanEntity);
                                }
                            } else {
                                LoanMgntBaseInfoEntity loanEntity = new LoanMgntBaseInfoEntity();
                                loanEntity.setLoanMgntUnqNo(loanMgntUnqNo);
                                loanEntity.setStoreId(entity.getStoreId());
                                loanEntity.setUseAmtTotal( Long.valueOf ( (entity.getPchOdrDtlInfo().getPodrQty() - reqEntity.getShmtQty()) * entity.getPchOdrDtlInfo().getUnitAmt()));
                                loanList.add(loanEntity);
                            }
                        }

                        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.setShmtReqUnqNo(shmtReqUnqNo);
                    inaddDtlEntity.setShmtReqDtlNo(Integer.toString(dtlNo));
                    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.setWaitQty(entity.getPchOdrDtlInfo().getPodrQty());
                    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.setShmtReqUnqNo(shmtReqUnqNo);
                    inaddDeliDtlEntity.setShmtReqDtlNo(Integer.toString(dtlNo));
                    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(instShmtOdrRequest.getDlvSchDt().replaceAll("\\.", ""));
                    shmtBaseEntity.setWhsId(entity.getWhsId());
                    shmtBaseEntity.setLocation(entity.getLocation());

                    //납품서 데이타 생성
                    deliBaseEntity.setDlvSttmtUnqNo(dlvSttmtUnqNo);
                    deliBaseEntity.setSpplyId(null);
                    deliBaseEntity.setSpplyNm(null);
                    deliBaseEntity.setStoreId(entity.getStoreId());
                    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("W02");
                    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.setWaitQty(entity.getPchOdrDtlInfo().getPodrQty());
                    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);
                    inaddDeliDtlEntity.setShmtReqUnqNo(shmtReqUnqNo);
                    inaddDeliDtlEntity.setShmtReqDtlNo("10");

                    deliDtlList.add(inaddDeliDtlEntity);

                }


            }  //=> for문 마지막

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


            // 납품수량 변동발생시 처리
            if (loanList.size() > 0) {
                loanStateMapper.updateListLoanMinusProc(userId, loanList);
            }


            // 재고수량 변동 및 안전비율계산(없애기로함) 처리후 저장함함

            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(fnGetDealNo(32, "")); // 재고관리상세번호

                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())
                        .dlvSttmtUnqNo(m.getDlvSttmtUnqNo() == null ? "" : m.getDlvSttmtUnqNo())
                        .build())
                .collect(Collectors.toList());
        return GridResponse.toDTO(gridPage, gridTotal, gridRecords, gridRows);
    }

    /* 납품서 정보 */
    public InvInfoResponse selectInvInfo(String brandId, String dlvSttmtUnqNo) throws Exception {

        DeliInfoMgntEntity entity = shmtOdrMapper.selectInvInfo(brandId, dlvSttmtUnqNo);
        List<DeliDtlMgntEntity> dtlEntity = shmtOdrMapper.selectInvDtlList(brandId, dlvSttmtUnqNo);


        // 공급사
        // 배송처 정보
        BrandEntity brandEntity = brandMapper.selectBrandInfo(brandId);

        if ("DL01".equals(entity.getDeliDvsn())) {
            //브랜드정보 배송
            entity.setDlvBsnsRegno(brandEntity.getBsnsRegNo());
            entity.setDlvNm(brandEntity.getBrandNm());
            entity.setDlvOwnerNm(brandEntity.getOwnerNm());
            entity.setDlvAddr(brandEntity.getAddr1() + " " + brandEntity.getAddr2());

        } else {
            //공급사 배송
            SpplyEntity dlv_spplyEntity = supplyMapper.selectSpplyInfo(brandId, entity.getSpplyId());
            entity.setDlvBsnsRegno(dlv_spplyEntity.getBsnsRegNo());
            entity.setDlvNm(dlv_spplyEntity.getSpplyNm());
            entity.setDlvOwnerNm(dlv_spplyEntity.getOwnerNm());
            entity.setDlvAddr(dlv_spplyEntity.getAddr1() + " " + dlv_spplyEntity.getAddr2());
        }


        //발주처 정보
        if ("W01".equals(entity.getWhsDvsn())) {
            //납품창고 본사
            entity.setPoBsnsRegno(brandEntity.getBsnsRegNo());
            entity.setPoNm(brandEntity.getBrandNm());
            entity.setPoOwnerNm(brandEntity.getOwnerNm());
            entity.setPoAddr(brandEntity.getAddr1() + " " + brandEntity.getAddr2());
        } else {
            //납품창고 매장
            StoreBaseInfoEntity whs_storeBaseInfoEntity = storeBaseInfoMapper.selectStoreInfo(brandId, entity.getStoreId());
            entity.setPoBsnsRegno(whs_storeBaseInfoEntity.getBsnsRegNo());
            entity.setPoNm(whs_storeBaseInfoEntity.getStoreNm());
            entity.setPoOwnerNm(whs_storeBaseInfoEntity.getOwnerNm());
            entity.setPoAddr(whs_storeBaseInfoEntity.getAddr1() + " " + whs_storeBaseInfoEntity.getAddr2());
        }

        // 브랜드 로고 brand_logo_file_no
        List<FileEntity> logFileList = null;
        if (!"".equals(brandEntity.getBrandLogoFileNo())) {
            logFileList = fileMapper.selectFileList(brandEntity.getBrandLogoFileNo());
        } else {
            logFileList = new ArrayList<FileEntity>();
        }

        return InvInfoResponse.toDTO(entity, dtlEntity, logFileList);
    }


    /*
     출하 대상 그리드 리스트 조회
    */
    public GridResponse selectSpplyTargetOdrGridList(String sBrandId, String fromDt, String toDt, 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 = shmtOdrMapper.selectSpplyTargetOdrGridCnt(sBrandId, fromDt, toDt, sSpplyId, sWhsId, sItemNm);
        int gridTotal = fnCalculateGridTotal(gridSize, gridRecords);
        List<PchOdrBaseInfoEntity> entities = shmtOdrMapper.selectSpplyTargetOdrGridList(sBrandId, fromDt, toDt, sSpplyId, sWhsId, sItemNm, gridRequest);
        List<Object> gridRows = entities.stream()
                .map(m -> SpplyTargerOdrSearchListResponse.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())
                        .podrAmt(m.getPchOdrDtlInfo() == null ? 0 : m.getPchOdrDtlInfo().getPodrAmt() == null ? 0 : m.getPchOdrDtlInfo().getPodrAmt())
                        .dlvReqDt(m.getDlvReqDt() == null ? "" : m.getDlvReqDt())
                        .build())
                .collect(Collectors.toList());
        return GridResponse.toDTO(gridPage, gridTotal, gridRecords, gridRows);
    }


    /* 공급사 납품서 생성 초기 정보 */
    public SpplyInvInitResponse selectSpplyShmtOdrInfo(String brandId, String spplyId, String pchPodrUnqNo) throws Exception {
        PchOdrBaseInfoEntity entity = shmtOdrMapper.selectSpplyShmtOdrInfo(brandId, spplyId, pchPodrUnqNo);
        List<PchOdrDtlPtclEntity> dtlEntity = shmtOdrMapper.selectSpplyShmtOdrList(pchPodrUnqNo);

        return SpplyInvInitResponse.toDTO(entity, dtlEntity);
    }

    /* 공급사 납품서 생성 저장 */
    @Transactional
    public void saveSpplyInv(String userId, SaveSpplyDlvRequest saveSpplyDlvRequest) throws Exception {
        try {

            List<PchOdrDtlPtclEntity> gridInsertData = saveSpplyDlvRequest.toCodeEntities(saveSpplyDlvRequest.getGridInsertData());
            List<PchOdrBaseInfoEntity> jobList = shmtOdrMapper.selectShmtJobDataList(saveSpplyDlvRequest.getBrandId(), gridInsertData);
            long shmtTotalAmt = 0;
            String expryDate = "";
            int shmtQty = 0;
            String dlvSttmtUnqNo = "";
            String storeId = "" ;
            long chgLoanAmt = 0 ;

            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);
                            }
                        }

                        // 동일 납품처가 아니면 오류 처리
                        if (!"".equals(storeId) && !storeId.equals(entity.getStoreId())) {
                            throw new GlobalException(SystemMessageCode.ERR_NEQWHSID);
                        }

                        if (reqEntity.getShmtQty() < entity.getPchOdrDtlInfo().getPodrQty()) {

                            chgLoanAmt = chgLoanAmt + (entity.getPchOdrDtlInfo().getPodrQty() - reqEntity.getShmtQty()) * entity.getPchOdrDtlInfo().getUnitAmt();
                        }

                        expryDate = reqEntity.getExpryDate().replaceAll("\\.", "");
                        shmtQty = reqEntity.getShmtQty();

                        break;
                    }
                }

                shmtTotalAmt = shmtTotalAmt + (entity.getPchOdrDtlInfo().getUnitAmt() * shmtQty);
                if (i == 0 ) {
                    dlvSttmtUnqNo = fnGetDealNo(15, ""); // 납품서번호
                    deliBaseEntity.setDlvSttmtUnqNo(dlvSttmtUnqNo);
                    deliBaseEntity.setSpplyId(entity.getSpplyId());
                    deliBaseEntity.setSpplyNm(entity.getSpplyNm());
                    deliBaseEntity.setStoreId(entity.getStoreId());
                    //deliBaseEntity.setDlvAmt(shmtTotalAmt);
                    deliBaseEntity.setDlvMgrNm(saveSpplyDlvRequest.getDlvMgrNm());
                    deliBaseEntity.setDlvMgrTelNo(saveSpplyDlvRequest.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(saveSpplyDlvRequest.getDlvSchDt().replaceAll("\\.", ""));
                    deliBaseEntity.setDlvCmpltDt(null);
                    deliBaseEntity.setWhsId(entity.getWhsId());
                    deliBaseEntity.setLocation(entity.getLocation());
                    if ("".equals(entity.getStoreId()) || entity.getStoreId() == null) {
                        deliBaseEntity.setWhsDvsn("W01");
                    } else {
                        deliBaseEntity.setWhsDvsn("W02");
                    }
                    deliBaseEntity.setBrandId(saveSpplyDlvRequest.getBrandId());
                }

                int dtlNo = (i+1) * 10;

                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);

            }

            deliBaseEntity.setDlvAmt(shmtTotalAmt);
            shmtOdrMapper.insertDeliInfoMngt(userId, deliBaseEntity);
            shmtOdrMapper.insertDeliDtlPtcl(userId, deliDtlList);

            // 변동금액 시 여신수정
            if (chgLoanAmt > 0 ) {
                String loanMgntUnqNo = storeBaseInfoMapper.selectStoreLoanMgntUnqNo(storeId);
                loanStateMapper.updateloanMinusInstProc(loanMgntUnqNo, storeId, chgLoanAmt);
            }


            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 selectDeliGridList(String sBrandId, String dtGubun,  String fromDt, String toDt, String sDlvStCd, 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 = shmtOdrMapper.selectDeliGridCnt(sBrandId, dtGubun, fromDt, toDt, sDlvStCd, sSpplyId, sWhsId, sItemNm);
        int gridTotal = fnCalculateGridTotal(gridSize, gridRecords);
        List<DeliInfoMgntEntity> entities = shmtOdrMapper.selectDeliGridList(sBrandId, dtGubun, fromDt, toDt, sDlvStCd, sSpplyId, sWhsId, sItemNm, gridRequest);
        List<Object> gridRows = entities.stream()
                .map(m -> DeliDtlSearchListResponse.builder()
                        .viewCd("R")
                        .brandId(m.getBrandId() == null ? "" : m.getBrandId())
                        .brandNm(m.getBrandNm() == null ? "" : m.getBrandNm())
                        .dlvSttmtUnqNo(m.getDlvSttmtUnqNo() == null ? "" : m.getDlvSttmtUnqNo())
                        .pchPodrUnqNo(m.getDeliDtlMgntInfo() == null ? "" : m.getDeliDtlMgntInfo().getPchPodrUnqNo() == null ? "" :  m.getDeliDtlMgntInfo().getPchPodrUnqNo())
                        .pchPodrDtlNo(m.getDeliDtlMgntInfo() == null ? "" : m.getDeliDtlMgntInfo().getPchPodrDtlNo() == null ? "" :  m.getDeliDtlMgntInfo().getPchPodrDtlNo())
                        .spplyId(m.getSpplyId() == null ? "" : m.getSpplyId())
                        .spplyNm(m.getSpplyNm() == null ? "" : m.getSpplyNm())
                        .dlvStCd(m.getDlvStCd() == null ? "" : m.getDlvStCd())
                        .dlvStNm(m.getDlvStNm() == null ? "" : m.getDlvStNm())
                        .whsId(m.getWhsId() == null ? "" :m.getWhsId())
                        .location(m.getLocation() == null ? "" : m.getLocation())
                        .whsNm(m.getWhsNm() == null ? "" : m.getWhsNm() + " - " + m.getLocationNm())
                        .podrRegDt(m.getPodrRegDt() == null ? "" : m.getPodrRegDt())
                        .dlvRegDt(m.getDlvRegDt() == null ? "" : m.getDlvRegDt())
                        .dlvReqDt(m.getDlvReqDt() == null ? "" : m.getDlvReqDt())
                        .dlvSchDt(m.getDlvSchDt() == null ? "" : m.getDlvSchDt())
                        .dlvCmpltDt(m.getDlvCmpltDt() == null ? "" : m.getDlvCmpltDt())
                        .itemId(m.getDeliDtlMgntInfo() == null ? "" : m.getDeliDtlMgntInfo().getItemId() == null ? "" : m.getDeliDtlMgntInfo().getItemId())
                        .itemNm(m.getDeliDtlMgntInfo() == null ? "" : m.getDeliDtlMgntInfo().getItemNm() == null ? "" : m.getDeliDtlMgntInfo().getItemNm())
                        .podrQty(m.getDeliDtlMgntInfo() == null ? 0 : m.getDeliDtlMgntInfo().getPodrQty() == null ? 0 : m.getDeliDtlMgntInfo().getPodrQty())
                        .dlvQty(m.getDeliDtlMgntInfo() == null ? 0 : m.getDeliDtlMgntInfo().getDlvQty() == null ? 0 : m.getDeliDtlMgntInfo().getDlvQty())
                        .unit(m.getDeliDtlMgntInfo() == null ? "" : m.getDeliDtlMgntInfo().getUnit() == null ? "" : m.getDeliDtlMgntInfo().getUnit())
                        .unitAmt(m.getDeliDtlMgntInfo() == null ? 0 : m.getDeliDtlMgntInfo().getUnitAmt() == null ? 0 : m.getDeliDtlMgntInfo().getUnitAmt())
                        .dlvMgrNm(m.getDlvMgrNm() == null ? "" : m.getDlvMgrNm())
                        .dlvMgrTelNo(m.getDlvMgrTelNo() == null ? "" : m.getDlvMgrTelNo())
                        .whsDvsn(m.getWhsDvsn() == null ? "" : m.getWhsDvsn())
                        .whsDvsnNm(m.getWhsDvsnNm() == null ? "" : m.getWhsDvsnNm())
                        .build())
                .collect(Collectors.toList());
        return GridResponse.toDTO(gridPage, gridTotal, gridRecords, gridRows);
    }


    /*
      공급사  - 납품서 현황 그리드 리스트 조회
     */
    public GridResponse selectSpplyDeliGridList(String sBrandId, String fromDt, String toDt, 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 = shmtOdrMapper.selectSpplyDeliGridCnt(sBrandId,  fromDt, toDt, sSpplyId, sWhsId, sItemNm);
        int gridTotal = fnCalculateGridTotal(gridSize, gridRecords);
        List<DeliInfoMgntEntity> entities = shmtOdrMapper.selectSpplyDeliGridList(sBrandId, fromDt, toDt, sSpplyId, sWhsId, sItemNm, gridRequest);
        List<Object> gridRows = entities.stream()
                .map(m -> DeliDtlSearchListResponse.builder()
                        .viewCd("R")
                        .brandId(m.getBrandId() == null ? "" : m.getBrandId())
                        .brandNm(m.getBrandNm() == null ? "" : m.getBrandNm())
                        .dlvSttmtUnqNo(m.getDlvSttmtUnqNo() == null ? "" : m.getDlvSttmtUnqNo())
                        .spplyId(m.getSpplyId() == null ? "" : m.getSpplyId())
                        .spplyNm(m.getSpplyNm() == null ? "" : m.getSpplyNm())
                        .dlvStCd(m.getDlvStCd() == null ? "" : m.getDlvStCd())
                        .dlvStNm(m.getDlvStNm() == null ? "" : m.getDlvStNm())
                        .whsId(m.getWhsId() == null ? "" :m.getWhsId())
                        .location(m.getLocation() == null ? "" : m.getLocation())
                        .whsNm(m.getWhsNm() == null ? "" : m.getWhsNm() + " - " + m.getLocationNm())
                        .podrRegDt(m.getPodrRegDt() == null ? "" : m.getPodrRegDt())
                        .dlvRegDt(m.getDlvRegDt() == null ? "" : m.getDlvRegDt())
                        .dlvReqDt(m.getDlvReqDt() == null ? "" : m.getDlvReqDt())
                        .dlvSchDt(m.getDlvSchDt() == null ? "" : m.getDlvSchDt())
                        .dlvCmpltDt(m.getDlvCmpltDt() == null ? "" : m.getDlvCmpltDt())
                        .itemId(m.getDeliDtlMgntInfo() == null ? "" : m.getDeliDtlMgntInfo().getItemId() == null ? "" : m.getDeliDtlMgntInfo().getItemId())
                        .itemNm(m.getDeliDtlMgntInfo() == null ? "" : m.getDeliDtlMgntInfo().getItemNm() == null ? "" : m.getDeliDtlMgntInfo().getItemNm())
                        .podrQty(m.getDeliDtlMgntInfo() == null ? 0 : m.getDeliDtlMgntInfo().getPodrQty() == null ? 0 : m.getDeliDtlMgntInfo().getPodrQty())
                        .dlvQty(m.getDeliDtlMgntInfo() == null ? 0 : m.getDeliDtlMgntInfo().getDlvQty() == null ? 0 : m.getDeliDtlMgntInfo().getDlvQty())
                        .unit(m.getDeliDtlMgntInfo() == null ? "" : m.getDeliDtlMgntInfo().getUnit() == null ? "" : m.getDeliDtlMgntInfo().getUnit())
                        .unitAmt(m.getDeliDtlMgntInfo() == null ? 0 : m.getDeliDtlMgntInfo().getUnitAmt() == null ? 0 : m.getDeliDtlMgntInfo().getUnitAmt())
                        .dlvAmt(m.getDeliDtlMgntInfo() == null ? 0 : m.getDeliDtlMgntInfo().getDlvAmt() == null ? 0 : m.getDeliDtlMgntInfo().getDlvAmt())
                        .dlvMgrNm(m.getDlvMgrNm() == null ? "" : m.getDlvMgrNm())
                        .dlvMgrTelNo(m.getDlvMgrTelNo() == null ? "" : m.getDlvMgrTelNo())
                        .build())
                .collect(Collectors.toList());
        return GridResponse.toDTO(gridPage, gridTotal, gridRecords, gridRows);
    }

    /*
      입고처리 그리드 리스트 조회
     */
    public GridResponse selectWarehouseTargetList(String userId, String sBrandId, String sStroeId, String fromDt, String toDt, String sWhsId, String sSpplyId, String sDlvSttmtUnqNo, String sItemNm, GridRequest gridRequest) throws Exception {
        int gridPage = gridRequest.getGridPage();
        int gridSize = gridRequest.getGridSize();

        UserMngEntity uEntity = userMngMapper.selectGroupUserInfo(userId);
        if ("50".equals(uEntity.getAuthTpCd())) {
            if ("".equals(sStroeId)) {
                throw new GlobalException(SystemMessageCode.ERR_NONSTOREID);
            }
        }

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

        String sStoreId = "";

        int gridRecords = shmtOdrMapper.selectWarehouseTargetGridCnt(sBrandId,sStoreId,  fromDt, toDt, sWhsId, sSpplyId, sDlvSttmtUnqNo, sItemNm);
        int gridTotal = fnCalculateGridTotal(gridSize, gridRecords);
        List<DeliInfoMgntEntity> entities = shmtOdrMapper.selectWarehouseTargetGridList(sBrandId,  sStoreId,  fromDt, toDt, sWhsId, sSpplyId, sDlvSttmtUnqNo, sItemNm, gridRequest);
        List<Object> gridRows = entities.stream()
                .map(m -> WarehouseTargetResponse.builder()
                        .viewCd("R")
                        .brandId(m.getBrandId() == null ? "" : m.getBrandId())
                        .brandNm(m.getBrandNm() == null ? "" : m.getBrandNm())
                        .dlvSttmtUnqNo(m.getDlvSttmtUnqNo() == null ? "" : m.getDlvSttmtUnqNo())
                        .dlvSttmtDtlNo(m.getDeliDtlMgntInfo() == null ? "" : m.getDeliDtlMgntInfo().getDlvSttmtDtlNo() == null ? "" : m.getDeliDtlMgntInfo().getDlvSttmtDtlNo())
                        .itemId(m.getDeliDtlMgntInfo() == null ? "" : m.getDeliDtlMgntInfo().getItemId() == null ? "" : m.getDeliDtlMgntInfo().getItemId())
                        .itemNm(m.getDeliDtlMgntInfo() == null ? "" : m.getDeliDtlMgntInfo().getItemNm() == null ? "" : m.getDeliDtlMgntInfo().getItemNm())
                        .podrQty(m.getDeliDtlMgntInfo() == null ? 0 : m.getDeliDtlMgntInfo().getPodrQty() == null ? 0 : m.getDeliDtlMgntInfo().getPodrQty())
                        .dlvQty(m.getDeliDtlMgntInfo() == null ? 0 : m.getDeliDtlMgntInfo().getDlvQty() == null ? 0 : m.getDeliDtlMgntInfo().getDlvQty())
                        //.whsQty(m.getDeliDtlMgntInfo() == null ? 0 : m.getDeliDtlMgntInfo().getWhsQty() == null ? 0 : m.getDeliDtlMgntInfo().getWhsQty())
                        .whsAmt(m.getDeliDtlMgntInfo() == null ? 0 : m.getDeliDtlMgntInfo().getWhsAmt() == null ? 0 : m.getDeliDtlMgntInfo().getWhsAmt())
                        .unit(m.getDeliDtlMgntInfo() == null ? "" : m.getDeliDtlMgntInfo().getUnit() == null ? "" : m.getDeliDtlMgntInfo().getUnit())
                        .unitAmt(m.getDeliDtlMgntInfo() == null ? 0 : m.getDeliDtlMgntInfo().getUnitAmt() == null ? 0 : m.getDeliDtlMgntInfo().getUnitAmt())
                        .whsId(m.getWhsId() == null ? "" :m.getWhsId())
                        .location(m.getLocation() == null ? "" : m.getLocation())
                        .whsNm(m.getWhsNm() == null ? "" : m.getWhsNm() + " - " + m.getLocationNm())
                        .dlvReqDt(m.getDlvReqDt() == null ? "" : m.getDlvReqDt())
                        .dlvSchDt(m.getDlvSchDt() == null ? "" : m.getDlvSchDt())
                        .dlvMgrNm(m.getDlvMgrNm() == null ? "" : m.getDlvMgrNm())
                        .dlvMgrTelNo(m.getDlvMgrTelNo() == null ? "" : m.getDlvMgrTelNo())
                        .pchPodrUnqNo(m.getDeliDtlMgntInfo() == null ? "" : m.getDeliDtlMgntInfo().getPchPodrUnqNo() == null ? "" : m.getDeliDtlMgntInfo().getPchPodrUnqNo())
                        .pchPodrDtlNo(m.getDeliDtlMgntInfo() == null ? "" : m.getDeliDtlMgntInfo().getPchPodrDtlNo() == null ? "" : m.getDeliDtlMgntInfo().getPchPodrDtlNo())
                        .pchReqUnqNo(m.getDeliDtlMgntInfo() == null ? "" : m.getDeliDtlMgntInfo().getPchReqUnqNo() == null ? "" : m.getDeliDtlMgntInfo().getPchReqUnqNo())
                        .pchReqDltNo(m.getDeliDtlMgntInfo() == null ? "" : m.getDeliDtlMgntInfo().getPchReqDtlNo() == null ? "" : m.getDeliDtlMgntInfo().getPchReqDtlNo())
                        .spplyId(m.getSpplyId() == null ? "" : m.getSpplyId())
                        .spplyNm(m.getSpplyNm() == null ? "" : m.getSpplyNm())
                        .build())
                .collect(Collectors.toList());
        return GridResponse.toDTO(gridPage, gridTotal, gridRecords, gridRows);
    }

    /* 입고처리 저장 */
    @Transactional
    public void saveWarehouseProc(String userId, SaveWarehouseProcRequest saveWarehouseProcRequest) throws Exception {
        try {

            List<WhsProcInfoPtclEntity> gridInsertData = saveWarehouseProcRequest.toCodeEntities(saveWarehouseProcRequest.getGridInsertData());
            List<DeliDtlMgntEntity> serarchList = new ArrayList<DeliDtlMgntEntity>();
            if (gridInsertData.size() > 0) {
                for (int i = 0 ; i < gridInsertData.size() ; i++) {
                    WhsProcInfoPtclEntity whsProcData = gridInsertData.get(i);
                    DeliDtlMgntEntity deliData = new DeliDtlMgntEntity();
                    deliData.setDlvSttmtDtlNo(whsProcData.getDlvSttmtUnqNo() + whsProcData.getDlvSttmtDtlNo());
                    serarchList.add(deliData);
                }

                List<DeliInfoMgntEntity> targetList  =   shmtOdrMapper.selectWarehouseProcList(saveWarehouseProcRequest.getBrandId(), saveWarehouseProcRequest.getWhsId(), serarchList);

                List<WhsProcInfoPtclEntity> gridUpdateData = new ArrayList<WhsProcInfoPtclEntity>();
                List<StckMgntBaseInfoEntity> wareGridUpdateData = new ArrayList<StckMgntBaseInfoEntity>();
                List<DeliDtlMgntEntity> deliDtlGridUpdateData = new ArrayList<DeliDtlMgntEntity>();
                List<ShmtOdrDtlEntity> shmtDtlGridUpdateData = new ArrayList<ShmtOdrDtlEntity>();
                List<PchOdrDtlPtclEntity> PchOdrDtlGridUpdateData = new ArrayList<PchOdrDtlPtclEntity>();
                List<StckMgntDtlHistEntity> stckMgntDtlHistList= new ArrayList<StckMgntDtlHistEntity>();

                //정산을 위한 입고처리 데이타
                List<WhsProcInfoPtclEntity> sttlList = new ArrayList<WhsProcInfoPtclEntity>();

                // loan_mgnt_unq_no 매장납품일 경우
                //selectStoreLoanMgntUnqNo
                String loanMgntUnqNo = "";
                String storeWhsUseYn = "Y";
                long loanAmt = 0 ; // 여신차감할 금액 (사용금액 - 여신차감금액,   잔액금액 - 여신차감금액)
                if (!"".equals(saveWarehouseProcRequest.getStoreId())) {
                    loanMgntUnqNo = storeBaseInfoMapper.selectStoreLoanMgntUnqNo(saveWarehouseProcRequest.getStoreId());

                    // 창고사용여부 값 가져오기
                    StoreBaseInfoEntity whsUseInfo = storeBaseInfoMapper.selectStoreLoanInfo(saveWarehouseProcRequest.getBrandId(), saveWarehouseProcRequest.getStoreId());
                    storeWhsUseYn = whsUseInfo.getWhsUseYn();

                }

                // 우선 입고수량과 납품수량 비교를 처리함
                for (int i = 0 ; i < gridInsertData.size() ; i++) {
                    WhsProcInfoPtclEntity whsProcData = gridInsertData.get(i);

                    for (int j = 0  ; j < targetList.size() ; j++) {
                        DeliInfoMgntEntity targetData = targetList.get(j);
                        if (whsProcData.getDlvSttmtUnqNo().equals(targetData.getDlvSttmtUnqNo()) && whsProcData.getDlvSttmtDtlNo().equals(targetData.getDeliDtlMgntInfo().getDlvSttmtDtlNo())) {
                            if (whsProcData.getWhsQty() > targetData.getDeliDtlMgntInfo().getDlvQty()) {
                                 // 오류 처리
                                throw new GlobalException(SystemMessageCode.ERR_NOTWAREHOUSE);
                            }
                            int whsQty = whsProcData.getWhsQty();
                            // 입고번호 생성
                            whsProcData.setWhsMgntUnqNo(fnGetDealNo(17,""));
                            whsProcData.setDlvSttmtDtlNo(targetData.getDeliDtlMgntInfo().getDlvSttmtDtlNo());
                            whsProcData.setDlvSttmtUnqNo(targetData.getDlvSttmtUnqNo());
                            whsProcData.setBrandId(targetData.getBrandId());
                            whsProcData.setStoreId(targetData.getStoreId());
                            whsProcData.setWhsId(targetData.getWhsId());
                            whsProcData.setLocation(targetData.getLocation());
                            if (!"".equals(saveWarehouseProcRequest.getStoreId()) && !"".equals(targetData.getSpplyId())) {
                                whsProcData.setSpplyId(null);
                                whsProcData.setSpplyNm(null);
                            } else {
                                whsProcData.setSpplyId(targetData.getSpplyId());
                                whsProcData.setSpplyNm(targetData.getSpplyNm());
                            }
                            whsProcData.setWhsDvsn(targetData.getWhsDvsn());
                            whsProcData.setPodrQty(targetData.getDeliDtlMgntInfo().getPodrQty());
                            whsProcData.setDlvQty(targetData.getDeliDtlMgntInfo().getDlvQty());
                            whsProcData.setUnit(targetData.getDeliDtlMgntInfo().getUnit());

                            if (!"".equals(saveWarehouseProcRequest.getStoreId())) {
                                whsProcData.setUnitAmt(targetData.getDeliDtlMgntInfo().getStoreUnitAmt());
                            } else {
                                whsProcData.setUnitAmt(targetData.getDeliDtlMgntInfo().getUnitAmt());
                            }


                            whsProcData.setDlvReqDt(targetData.getDlvReqDt());
                            whsProcData.setDlvSchDt(targetData.getDlvSchDt());
                            whsProcData.setWhsCnfmNm(userId);
                            whsProcData.setDlvMgrNm(targetData.getDlvMgrNm());
                            whsProcData.setDlvMgrTelNo(targetData.getDlvMgrTelNo());
                            whsProcData.setDlvMgrEmal(targetData.getDlvMgrEmal());
                            whsProcData.setDlvMgrMblNo(targetData.getDlvMgrMblNo());
                            whsProcData.setItemId(targetData.getDeliDtlMgntInfo().getItemId());
                            whsProcData.setItemNm(targetData.getDeliDtlMgntInfo().getItemNm());
                            if (!"".equals(saveWarehouseProcRequest.getStoreId())) {
                                whsProcData.setWhsAmt(Long.valueOf(targetData.getDeliDtlMgntInfo().getStoreUnitAmt() * whsProcData.getWhsQty()));
                            } else {
                                whsProcData.setWhsAmt(Long.valueOf(targetData.getDeliDtlMgntInfo().getUnitAmt() * whsProcData.getWhsQty()));
                            }

                            whsProcData.setWhsDlvChrg(null);
                            //whsProcData.setDlvMgrId(targetData.getdlvmgr);
                            whsProcData.setDlvCnfmDocFileNo(whsProcData.getDlvCnfmDocFileNo());
                            whsProcData.setSttlYn("N");
                            whsProcData.setPchPodrUnqNo(targetData.getDeliDtlMgntInfo().getPchPodrUnqNo());
                            whsProcData.setPchPodrDtlNo(targetData.getDeliDtlMgntInfo().getPchPodrDtlNo());
                            whsProcData.setPchReqUnqNo(targetData.getDeliDtlMgntInfo().getPchReqUnqNo());
                            whsProcData.setPchReqDtlNo(targetData.getDeliDtlMgntInfo().getPchReqDtlNo());
                            whsProcData.setShmtReqUnqNo(targetData.getDeliDtlMgntInfo().getShmtReqUnqNo());
                            whsProcData.setShmtReqDtlNo(targetData.getDeliDtlMgntInfo().getShmtReqDtlNo());

                            gridUpdateData.add(whsProcData);
                            sttlList.add(whsProcData);
                            ////////////////////////////////////////////
                            // 입고번호 생성
                            if (!"".equals(saveWarehouseProcRequest.getStoreId()) && "DL02".equals(targetData.getDlvDvsn())
                                    && !"".equals(targetData.getSpplyId()) && targetData.getSpplyId() != null) {
                                WhsProcInfoPtclEntity whsProcData1 = new WhsProcInfoPtclEntity();
                                whsProcData1.setWhsMgntUnqNo(fnGetDealNo(17, ""));
                                whsProcData1.setDlvSttmtDtlNo(targetData.getDeliDtlMgntInfo().getDlvSttmtDtlNo());
                                whsProcData1.setDlvSttmtUnqNo(targetData.getDlvSttmtUnqNo());
                                whsProcData1.setBrandId(targetData.getBrandId());
                                whsProcData1.setStoreId(null);
                                whsProcData1.setWhsId(targetData.getWhsId());
                                whsProcData1.setLocation(targetData.getLocation());
                                whsProcData1.setSpplyId(targetData.getSpplyId());
                                whsProcData1.setSpplyNm(targetData.getSpplyNm());
                                whsProcData1.setWhsDvsn(targetData.getWhsDvsn());
                                whsProcData1.setPodrQty(targetData.getDeliDtlMgntInfo().getPodrQty());
                                whsProcData1.setDlvQty(targetData.getDeliDtlMgntInfo().getDlvQty());
                                whsProcData1.setWhsQty(whsQty);
                                whsProcData1.setUnit(targetData.getDeliDtlMgntInfo().getUnit());
                                whsProcData1.setUnitAmt(targetData.getDeliDtlMgntInfo().getUnitAmt());

                                whsProcData1.setDlvReqDt(targetData.getDlvReqDt());
                                whsProcData1.setDlvSchDt(targetData.getDlvSchDt());
                                whsProcData1.setWhsCnfmNm(userId);
                                whsProcData1.setDlvMgrNm(targetData.getDlvMgrNm());
                                whsProcData1.setDlvMgrTelNo(targetData.getDlvMgrTelNo());
                                whsProcData1.setDlvMgrEmal(targetData.getDlvMgrEmal());
                                whsProcData1.setDlvMgrMblNo(targetData.getDlvMgrMblNo());
                                whsProcData1.setItemId(targetData.getDeliDtlMgntInfo().getItemId());
                                whsProcData1.setItemNm(targetData.getDeliDtlMgntInfo().getItemNm());
                                whsProcData1.setWhsAmt(Long.valueOf(targetData.getDeliDtlMgntInfo().getUnitAmt() * whsProcData.getWhsQty()));
                                whsProcData1.setWhsDlvChrg(null);
                                //whsProcData.setDlvMgrId(targetData.getdlvmgr);
                                whsProcData1.setDlvCnfmDocFileNo(whsProcData.getDlvCnfmDocFileNo());
                                whsProcData1.setSttlYn("N");
                                whsProcData1.setPchPodrUnqNo(targetData.getDeliDtlMgntInfo().getPchPodrUnqNo());
                                whsProcData1.setPchPodrDtlNo(targetData.getDeliDtlMgntInfo().getPchPodrDtlNo());
                                whsProcData1.setPchReqUnqNo(targetData.getDeliDtlMgntInfo().getPchReqUnqNo());
                                whsProcData1.setPchReqDtlNo(targetData.getDeliDtlMgntInfo().getPchReqDtlNo());
                                whsProcData1.setShmtReqUnqNo(targetData.getDeliDtlMgntInfo().getShmtReqUnqNo());
                                whsProcData1.setShmtReqDtlNo(targetData.getDeliDtlMgntInfo().getShmtReqDtlNo());

                                gridUpdateData.add(whsProcData1);
                            }

                            //////////////////////////////////////////

                            // 정산할때 함 여신관련한 여신차감할 입고금액 세팅
                            //loanAmt = loanAmt + (targetData.getDeliDtlMgntInfo().getUnitAmt() * whsProcData.getWhsQty());

                            // 재고처리를 위한 작업업
                            //if (!"".equals(saveWarehouseProcRequest.getStoreId())) {
                            if ("Y".toString().equals(storeWhsUseYn)) {
                                StckMgntBaseInfoEntity smbaseInfoEntity = new StckMgntBaseInfoEntity();
                                smbaseInfoEntity.setBrandId(saveWarehouseProcRequest.getBrandId());
                                smbaseInfoEntity.setWhsId(saveWarehouseProcRequest.getWhsId());
                                smbaseInfoEntity.setLocation(whsProcData.getLocation());
                                smbaseInfoEntity.setItemId(whsProcData.getItemId());
                                smbaseInfoEntity.setStckQty(whsProcData.getWhsQty());
                                smbaseInfoEntity.setUnit(whsProcData.getUnit());
                                wareGridUpdateData.add(smbaseInfoEntity);

                                // 만약 해당 창고의 품목이 없을 경우 insert


                                // 재고 이력정보 등록
                                StckMgntDtlHistEntity stckWHist = new StckMgntDtlHistEntity();
                                stckWHist.setStckMgntDtlNo(fnGetDealNo(37, ""));
                                stckWHist.setBrandId(saveWarehouseProcRequest.getBrandId());
                                stckWHist.setWhsId(saveWarehouseProcRequest.getWhsId());
                                stckWHist.setLocation(whsProcData.getLocation());
                                stckWHist.setItemId(whsProcData.getItemId());
                                stckWHist.setItemNm(targetData.getDeliDtlMgntInfo().getItemNm());
                                stckWHist.setInoutCd("IN");
                                stckWHist.setInoutQty(whsProcData.getWhsQty());
                                stckWHist.setChgDvsn("PIN");
                                stckWHist.setRelationNo(whsProcData.getWhsMgntUnqNo());
                                stckMgntDtlHistList.add(stckWHist);
                            }

                            //targetList
                            // 부족입고수량에 대해 원 출하창고 재고 원복
                            if ( !"".equals(targetData.getStoreId()) &&  !"".equals(targetData.getShmtWhsId())) {
                                if (whsProcData.getWhsQty() < targetData.getDeliDtlMgntInfo().getDlvQty()) {

                                    StckMgntBaseInfoEntity shmtbaseInfoEntity = new StckMgntBaseInfoEntity();
                                    shmtbaseInfoEntity.setBrandId(saveWarehouseProcRequest.getBrandId());
                                    shmtbaseInfoEntity.setWhsId(targetData.getShmtWhsId());
                                    shmtbaseInfoEntity.setLocation(targetData.getShmtLocation());
                                    shmtbaseInfoEntity.setItemId(whsProcData.getItemId());
                                    shmtbaseInfoEntity.setStckQty(targetData.getDeliDtlMgntInfo().getDlvQty() - whsProcData.getWhsQty());
                                    shmtbaseInfoEntity.setUnit(whsProcData.getUnit());
                                    wareGridUpdateData.add(shmtbaseInfoEntity);

                                    // 재고 이력정보 등록
                                    StckMgntDtlHistEntity stckShmtWHist = new StckMgntDtlHistEntity();
                                    stckShmtWHist.setStckMgntDtlNo(fnGetDealNo(37, ""));
                                    stckShmtWHist.setBrandId(saveWarehouseProcRequest.getBrandId());
                                    stckShmtWHist.setWhsId(targetData.getShmtWhsId());
                                    stckShmtWHist.setLocation(targetData.getShmtLocation());
                                    stckShmtWHist.setItemId(whsProcData.getItemId());
                                    stckShmtWHist.setItemNm(targetData.getDeliDtlMgntInfo().getItemNm());
                                    stckShmtWHist.setInoutCd("IN");
                                    stckShmtWHist.setInoutQty(targetData.getDeliDtlMgntInfo().getDlvQty() - whsProcData.getWhsQty());
                                    stckShmtWHist.setChgDvsn("PINR");
                                    stckShmtWHist.setRelationNo(whsProcData.getWhsMgntUnqNo());
                                    stckMgntDtlHistList.add(stckShmtWHist);
                                }
                            }

                            // 납품서 상태 정의  dlvSttmtUnqNo  dlvDtlStCd
                            DeliDtlMgntEntity deliDtlEntity = new DeliDtlMgntEntity();
                            deliDtlEntity.setDlvSttmtUnqNo(whsProcData.getDlvSttmtUnqNo());
                            deliDtlEntity.setDlvSttmtDtlNo(whsProcData.getDlvSttmtDtlNo());
                            if (whsProcData.getWhsQty() > 0 ) {
                                deliDtlEntity.setDlvDtlStCd("DLD1");
                            } else {
                                deliDtlEntity.setDlvDtlStCd("DLD2");
                            }
                            deliDtlGridUpdateData.add(deliDtlEntity);


                            // 출하지시 상태정의
                            if (!"".equals(whsProcData.getShmtReqUnqNo()) && whsProcData.getShmtReqUnqNo() != null) {
                                ShmtOdrDtlEntity shmtDtlData = new ShmtOdrDtlEntity();
                                shmtDtlData.setShmtReqUnqNo(whsProcData.getShmtReqUnqNo());
                                shmtDtlData.setShmtReqDtlNo(whsProcData.getPchReqDtlNo());
                                if (whsProcData.getWhsQty() > 0 ) {
                                    shmtDtlData.setShmtDtlStCd("SHMD2");
                                } else {
                                    shmtDtlData.setShmtDtlStCd("SHMD3");
                                }

                                shmtDtlGridUpdateData.add(shmtDtlData);
                            }

                            PchOdrDtlPtclEntity pchOdrDtlData = new PchOdrDtlPtclEntity();
                            pchOdrDtlData.setPchPodrUnqNo(whsProcData.getPchPodrUnqNo());
                            pchOdrDtlData.setPchPodrDtlNo(whsProcData.getPchPodrDtlNo());
                            if (whsProcData.getWhsQty() > 0 ) {
                                pchOdrDtlData.setPodrDtlStCd("POD4");

                                if (whsProcData.getWhsQty() < targetData.getDeliDtlMgntInfo().getDlvQty()) {
                                    loanAmt = loanAmt + ( (targetData.getDeliDtlMgntInfo().getDlvQty() - whsProcData.getWhsQty()) * whsProcData.getUnitAmt() ) ;
                                }
                            } else {
                                pchOdrDtlData.setPodrDtlStCd("POD2");

                                if (!"".equals(loanMgntUnqNo)) {
                                    loanAmt = loanAmt + ( targetData.getDeliDtlMgntInfo().getDlvQty() * whsProcData.getUnitAmt() ) ;
                                }
                            }

                            PchOdrDtlGridUpdateData.add(pchOdrDtlData);
                            break;
                        }


                    }  // or문 종료
                }

                    // 입고데이타 저장
                    shmtOdrMapper.insertWhsProcInfoPtcl(userId, gridUpdateData);

                    // 재고관련 정리 필요
                    //stockMngMapper.updateWarehouseStockQty(userId, wareGridUpdateData);
                    if (wareGridUpdateData.size() > 0) {
                        stockMngMapper.insertInOutStckMgntBaseInfo(userId, wareGridUpdateData);
                        stockMngMapper.insertMultiStckMgntDtlHist(userId, stckMgntDtlHistList);
                    }

                    // 납품서 상세 처리
                    shmtOdrMapper.updateDeliDtlStCd(userId, deliDtlGridUpdateData);

                    // 납품서 헤더 상태 처리
                    List<DeliInfoMgntEntity> deliInfoStList = shmtOdrMapper.selectDeliInfoStList(userId, deliDtlGridUpdateData);
                    shmtOdrMapper.updateDeliInfoStCd(userId, deliInfoStList);

                    // 출하지시서 상태 업데이트
                    if (shmtDtlGridUpdateData.size() > 0) {
                        shmtOdrMapper.updateShmtDtlStCd(userId,shmtDtlGridUpdateData );
                        List<ShmtOdrBaseEntity> shmtInfoStList = shmtOdrMapper.selectShmtInfoStList(userId, shmtDtlGridUpdateData);
                        shmtOdrMapper.updateShmtInfoStCd(userId, shmtInfoStList);
                    }


                    shmtOdrMapper.updatePchPodrDtlStCd(userId, PchOdrDtlGridUpdateData);

                    String pchPodrUnqNo = "";
                    for (int k = 0; k < PchOdrDtlGridUpdateData.size(); k++) {
                        if (!pchPodrUnqNo.equals(PchOdrDtlGridUpdateData.get(k).getPchPodrUnqNo())) {
                            pchPodrUnqNo = PchOdrDtlGridUpdateData.get(k).getPchPodrUnqNo();
                            String pchOdrStCd = pchOrdService.selectOdrDtlStatusList(pchPodrUnqNo);
                            pchOrdMapper.updateChgPodrStCd(userId, pchOdrStCd, pchPodrUnqNo);
                        }
                    }

                    // 발주 헤더가 취소면 해당 발주건에 대한 사용금액을 원복 처리한다.
                    if (!"".equals(loanMgntUnqNo) && loanAmt > 0) {
                        // 여신관련 정리 필요 loanAmt 업데이트
                        loanStateMapper.updateloanMinusInstProc(loanMgntUnqNo, saveWarehouseProcRequest.getStoreId(), loanAmt);
                    }

                    //선불 매장은 자동 정산처리함  입고정보 리스트 가져와 자동 정산처리함
                    if (!"".equals(saveWarehouseProcRequest.getStoreId())) {
                        String loanDvsn = storeBaseInfoMapper.selectStoreLoanDvsn(saveWarehouseProcRequest.getStoreId());
                        if ("LD01".equals(loanDvsn)) {
                            // 정산데이타 생성하고 정산 확정 처리까지 함  sttlReqMapper
                            if (sttlList.size() > 0) {
                                UserMngEntity uEntity = userMngMapper.selectGroupUserInfo(userId);
                                List<StlMgntDtlPtclEntity> insertSttlList = new ArrayList<StlMgntDtlPtclEntity>();

                                int dtlNo = 0 ;
                                String sttlMgntUnqNo = fnGetDealNo(37, "");
                                long sttlAmt = 0 ;
                                List<StlMgntDtlPtclEntity> sttlDataList = sttlReqMapper.selectSttlWhsPtclList(saveWarehouseProcRequest.getBrandId(), sttlList);
                                for (int k = 0 ; k < sttlDataList.size() ; k++) {
                                    dtlNo = dtlNo + 10 ;
                                    StlMgntDtlPtclEntity sttlDtl = sttlDataList.get(k);
                                    sttlDtl.setSttlMgntUnqNo(sttlMgntUnqNo);
                                    sttlDtl.setSttlMgntDtlNo(Integer.toString(dtlNo));
                                    sttlAmt = sttlAmt + sttlDtl.getWhsAmt();
                                    insertSttlList.add(sttlDtl);
                                } //정산 for문 종료
                                StlMgntBaseInfoEntity sttlMgntBase = sttlReqMapper.selectSttlWhsBaseInfo(saveWarehouseProcRequest.getBrandId(), sttlList);
                                sttlMgntBase.setSttlMgntUnqNo(sttlMgntUnqNo);
                                sttlMgntBase.setSttlReqAmt(sttlAmt);
                                sttlMgntBase.setSttlAmt(sttlAmt);
                                sttlMgntBase.setSttlRegMgrNm(uEntity.getUserNm());
                                sttlMgntBase.setSttlRegMgrId(userId);

                                sttlReqMapper.insertStlMgntBaseInfo(userId, sttlMgntBase);
                                sttlReqMapper.insertAutoStlMgntDtlPtcl(userId, insertSttlList);
                                shmtOdrMapper.updateWhsProcAutoSttl(userId, insertSttlList);

                                //여신금액 업데이트  및 이력
                                LoanMgntBaseInfoEntity loanBase = dsptMngMapper.selectLoanMgntBaseInfo(saveWarehouseProcRequest.getBrandId(), saveWarehouseProcRequest.getStoreId());
                                long trscBfBal = loanBase.getAcctBal();
                                long trscAfBal = loanBase.getAcctBal() - sttlAmt;       // 잔액에서 입고/수거금액 차감
                                //long useAmtTotal = loanBase.getUseAmtTotal() - sttlAmt; // 사용금액합계에서 입고/수거금액 차감

                                loanStateMapper.updateloanAutoSttl(userId, loanMgntUnqNo, saveWarehouseProcRequest.getStoreId(), sttlAmt);

                                LoanMgntDtlHstEntity hstEntity = new LoanMgntDtlHstEntity();
                                hstEntity.setLoanMgntUnqNo(loanMgntUnqNo);
                                hstEntity.setLoanRegDt(DateUtil.getCurrentDate());
                                hstEntity.setLoanRegTm(DateUtil.getCurrentTime());
                                hstEntity.setDpstPayDvsn(DpstPayDvsn.PAYMENT.getCd());
                                hstEntity.setMediaDvsn(MediaDvsn.SETTLMENT.getCd());
                                hstEntity.setPayType(PayType.STTL_PAY.getCd());
                                hstEntity.setTrscAmt(sttlAmt); // 거래금액
                                hstEntity.setPaymAmt(sttlAmt); // 지급금액
                                hstEntity.setTrscBfBal(trscBfBal);
                                hstEntity.setTrscAfBal(trscAfBal);
                                dsptMngMapper.insertLoanMgntDtlHst(userId, hstEntity);
                            }
                        }
                    }


            }

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


    /*
      입고 현황 그리드 리스트 조회  @Param("sBrandId") String sBrandId, @Param("sStoreId") String sStoreId,
      @Param("fromDt") String fromDt, @Param("toDt") String toDt, @Param("sPchPodrUnqNo") String sPchPodrUnqNo, @Param("sSpplyId") String sSpplyId, @Param("sWhsId") String sWhsId, @Param("sItemNm") String sItemNm
     */
    public GridResponse selectWarehouseGridList(String userId, String sBrandId, String sStoreId,  String fromDt, String toDt, String sPchPodrUnqNo, 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(".", "");

        UserMngEntity uEntity = userMngMapper.selectGroupUserInfo(userId);


        if ("50".equals(uEntity.getAuthTpCd())) {
            if ("".equals(sStoreId)) {
                throw new GlobalException(SystemMessageCode.ERR_NONSTOREID);
            }
        }

        int gridRecords = shmtOdrMapper.selectWarehouseCnt(sBrandId, sStoreId, fromDt, toDt, sPchPodrUnqNo, sSpplyId, sWhsId, sItemNm);
        int gridTotal = fnCalculateGridTotal(gridSize, gridRecords);
        List<WhsProcInfoPtclEntity> entities = shmtOdrMapper.selectWarehouseList(sBrandId, sStoreId, fromDt, toDt, sPchPodrUnqNo, sSpplyId, sWhsId, sItemNm, gridRequest);
        List<Object> gridRows = entities.stream()
                .map(m -> WarehouseSearchGridListResponse.builder()
                        .viewCd("R")
                        .pchPodrUnqNo(m.getPchPodrUnqNo() == null ? "" : m.getPchPodrUnqNo())
                        .pchPodrDtlNo(m.getPchPodrDtlNo() == null ? "" : m.getPchPodrDtlNo())
                        .dlvSttmtUnqNo(m.getDlvSttmtUnqNo() == null ? "" : m.getDlvSttmtUnqNo())
                        .dlvSttmtDtlNo(m.getDlvSttmtDtlNo() == null ? "" : m.getDlvSttmtDtlNo() )
                        .podrQty(m.getPodrQty() == null ? 0 : m.getPodrQty())
                        .dlvQty(m.getDlvQty() == null ? 0 : m.getDlvQty())
                        .whsQty(m.getWhsQty() == null ? 0 : m.getWhsQty())
                        .dlvReqDt(m.getDlvReqDt() == null ? "" : m.getDlvReqDt())
                        .dlvSchDt(m.getDlvSchDt() == null ? "" : m.getDlvSchDt())
                        .dlvCmpltDt(m.getDlvCmpltDt() == null ? "" : m.getDlvCmpltDt())
                        .whsCnfmNm(m.getWhsCnfmNm() == null ? "" : m.getWhsCnfmNm())
                        .dlvMgrNm(m.getDlvMgrNm() == null ? "" : m.getDlvMgrNm())
                        .dlvMgrTelNo(m.getDlvMgrTelNo() == null ? "" : m.getDlvMgrTelNo())
                        .itemId(m.getItemId() == null ? "" : m.getItemId())
                        .itemNm(m.getItemNm() == null ? "" : m.getItemNm())
                        .unit(m.getUnit() == null ? "" : m.getUnit())
                        .whsAmt(m.getWhsAmt() == null ? 0 : m.getWhsAmt())
                        .build())
                .collect(Collectors.toList());
        return GridResponse.toDTO(gridPage, gridTotal, gridRecords, gridRows);
    }



}



