package com.oqpo.api.service.inoutmng;


import com.oqpo.api.entity.inoutmng.*;
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.rtnmng.RtnOdrBaseInfoEntity;
import com.oqpo.api.entity.rtnmng.RtnOdrDtlPtclEntity;
import com.oqpo.api.entity.rtnmng.RtnProcInfoPtclEntity;
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.ColOdrMapper;
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.rtnmng.RtnOdrMapper;
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.service.CommonService;
import com.oqpo.api.service.pomng.PchOrdService;
import com.oqpo.api.service.rtnmng.RtnOdrService;
import com.oqpo.api.util.DateUtil;
import com.oqpo.api.web.dto.request.GridRequest;
import com.oqpo.api.web.dto.request.inoutmng.*;
import com.oqpo.api.web.dto.response.GridResponse;
import com.oqpo.api.web.dto.response.inoutmng.*;
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 ColOdrService extends CommonService {
    @Autowired
    private ColOdrMapper colOdrMapper;

    @Autowired
    private RtnOdrMapper rtnOdrMapper;

    @Autowired
    private RtnOdrService rtnOdrService;

    @Autowired
    private StockMngMapper stockMngMapper;


    @Autowired
    private BrandMapper brandMapper;

    @Autowired
    private SupplyMapper supplyMapper;

    @Autowired
    private StoreBaseInfoMapper storeBaseInfoMapper;

    @Autowired
    private FileMapper fileMapper;

    @Autowired
    private UserMngMapper userMngMapper;

    @Autowired
    private LoanStateMapper loanStateMapper;

    @Autowired
    private DsptMngMapper dsptMngMapper;


    /*
      수거 대상 그리드 리스트 조회
     */
    public GridResponse selectColTargetOdrGridList(String sBrandId, String fromDt, String toDt, String sWhsId, String sRtnWhsId, 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 = colOdrMapper.selectColTargetRtnGridCnt(sBrandId, fromDt, toDt, sWhsId, sRtnWhsId, sItemNm);
        int gridTotal = fnCalculateGridTotal(gridSize, gridRecords);
        List<RtnOdrBaseInfoEntity> entities = colOdrMapper.selectColTargetRtnGridList(sBrandId, fromDt, toDt, sWhsId,sRtnWhsId, sItemNm, gridRequest);
        List<Object> gridRows = entities.stream()
                .map(m -> ColTragetOdrSearchListResponse.builder()
                        .viewCd("R")
                        .brandId(m.getBrandId() == null ? "" : m.getBrandId())
                        .brandNm(m.getBrandNm() == null ? "" : m.getBrandNm())
                        .rtnPodrUnqNo(m.getRtnPodrUnqNo() == null ? "" : m.getRtnPodrUnqNo())
                        .rtnPodrDtlNo(m.getRtnOdrDtlInfo() == null ? "" : m.getRtnOdrDtlInfo().getRtnPodrDtlNo() == null ? "" : m.getRtnOdrDtlInfo().getRtnPodrDtlNo())
                        .rtnReqUnqNo(m.getRtnOdrDtlInfo() == null ? "" : m.getRtnOdrDtlInfo().getRtnReqUnqNo() == null ? "" : m.getRtnOdrDtlInfo().getRtnReqUnqNo())
                        .rtnReqDtlNo(m.getRtnOdrDtlInfo() == null ? "" : m.getRtnOdrDtlInfo().getRtnReqDtlNo() == null ? "" : m.getRtnOdrDtlInfo().getRtnReqDtlNo())
                        .itemId(m.getRtnOdrDtlInfo() == null ? "" : m.getRtnOdrDtlInfo().getItemId() == null ? "" : m.getRtnOdrDtlInfo().getItemId())
                        .itemNm(m.getRtnOdrDtlInfo() == null ? "" : m.getRtnOdrDtlInfo().getItemNm() == null ? "" : m.getRtnOdrDtlInfo().getItemNm())
                        .rtnWhsId(m.getRtnWhsId() == null ? "" : m.getRtnWhsId())
                        .rtnLocation(m.getRtnLocation() == null ? "" : m.getRtnLocation())
                        .rtnWhsNm(m.getRtnWhsNm() == null ? "" : m.getRtnWhsNm() + " - " + m.getRtnLocationNm())
                        .whsId(m.getWhsId() == null ? "" : m.getWhsId())
                        .location(m.getLocation() == null ? "" : m.getLocation())
                        .whsNm(m.getWhsNm() == null ? "" : m.getWhsNm() + " - " + m.getLocationNm())
                        .unitAmt(m.getRtnOdrDtlInfo() == null ? 0 : m.getRtnOdrDtlInfo().getUnitAmt() == null ? 0 : m.getRtnOdrDtlInfo().getUnitAmt())
                        .rtnReqQty(m.getRtnOdrDtlInfo() == null ? 0 : m.getRtnOdrDtlInfo().getRtnReqQty() == null ? 0 : m.getRtnOdrDtlInfo().getRtnReqQty())
                        .rtnOdrQty(m.getRtnOdrDtlInfo() == null ? 0 : m.getRtnOdrDtlInfo().getRtnOdrQty() == null ? 0 : m.getRtnOdrDtlInfo().getRtnOdrQty())
                        .colQty(m.getRtnOdrDtlInfo() == null ? 0 : m.getRtnOdrDtlInfo().getRtnOdrQty() == null ? 0 : m.getRtnOdrDtlInfo().getRtnOdrQty())
                        .rtnAmt(m.getRtnOdrDtlInfo() == null ? 0 : m.getRtnOdrDtlInfo().getRtnAmt() == null ? 0 : m.getRtnOdrDtlInfo().getRtnAmt())
                        .colReqDt(m.getColReqDt() == null ? "" : m.getColReqDt())
                        .storeId(m.getStoreId() == null ? "" : m.getStoreId())
                        .build())
                .collect(Collectors.toList());
        return GridResponse.toDTO(gridPage, gridTotal, gridRecords, gridRows);
    }

    /*
      수거지시 초기 그리드 리스트 조회
*/
    public GridResponse selectColInstOdrGridList(String sBrandId, InstInitColOdrRequest instInitColOdrRequest, GridRequest gridRequest) throws Exception {

        int gridPage = gridRequest.getGridPage();
        int gridSize = gridRequest.getGridSize();

        List<RtnOdrBaseInfoEntity> entities = colOdrMapper.selectColInstRtnGridList(sBrandId,instInitColOdrRequest.toCodeEntities(instInitColOdrRequest.getGridUpdateData()), gridRequest);

        int gridRecords = entities.size();
        int gridTotal = fnCalculateGridTotal(gridSize, gridRecords);

        List<Object> gridRows = entities.stream()
                .map(m -> ColInstInitOdrSearchListResponse.builder()
                        .viewCd("R")
                        .brandId(m.getBrandId() == null ? "" : m.getBrandId())
                        .brandNm(m.getBrandNm() == null ? "" : m.getBrandNm())
                        .rtnPodrUnqNo(m.getRtnPodrUnqNo() == null ? "" : m.getRtnPodrUnqNo())
                        .rtnPodrDtlNo(m.getRtnOdrDtlInfo() == null ? "" : m.getRtnOdrDtlInfo().getRtnPodrDtlNo() == null ? "" : m.getRtnOdrDtlInfo().getRtnPodrDtlNo())
                        .rtnReqUnqNo(m.getRtnOdrDtlInfo() == null ? "" : m.getRtnOdrDtlInfo().getRtnReqUnqNo() == null ? "" : m.getRtnOdrDtlInfo().getRtnReqUnqNo())
                        .rtnReqDtlNo(m.getRtnOdrDtlInfo() == null ? "" : m.getRtnOdrDtlInfo().getRtnReqDtlNo() == null ? "" : m.getRtnOdrDtlInfo().getRtnReqDtlNo())
                        .itemId(m.getRtnOdrDtlInfo() == null ? "" : m.getRtnOdrDtlInfo().getItemId() == null ? "" : m.getRtnOdrDtlInfo().getItemId())
                        .itemNm(m.getRtnOdrDtlInfo() == null ? "" : m.getRtnOdrDtlInfo().getItemNm() == null ? "" : m.getRtnOdrDtlInfo().getItemNm())
                        .rtnWhsId(m.getRtnWhsId() == null ? "" : m.getRtnWhsId())
                        .rtnLocation(m.getRtnLocation() == null ? "" : m.getRtnLocation())
                        .rntWhsNm(m.getRtnWhsNm() == null ? "" : m.getRtnWhsNm() + " - " + m.getRtnLocationNm())
                        .whsId(m.getWhsId() == null ? "" : m.getWhsId())
                        .location(m.getLocation() == null ? "" : m.getLocation())
                        .whsNm(m.getWhsNm() == null ? "" : m.getWhsNm() + " - " + m.getLocationNm())
                        .unitAmt(m.getRtnOdrDtlInfo() == null ? 0 : m.getRtnOdrDtlInfo().getUnitAmt() == null ? 0 : m.getRtnOdrDtlInfo().getUnitAmt())
                        .colQty(m.getRtnOdrDtlInfo() == null ? 0 : m.getRtnOdrDtlInfo().getColQty() == null ? 0 : m.getRtnOdrDtlInfo().getColQty())
                        .rtnOdrQty(m.getRtnOdrDtlInfo() == null ? 0 : m.getRtnOdrDtlInfo().getRtnOdrQty() == null ? 0 : m.getRtnOdrDtlInfo().getRtnOdrQty())
                        .rtnAmt(m.getRtnOdrDtlInfo() == null ? 0 : m.getRtnOdrDtlInfo().getRtnAmt() == null ? 0 : m.getRtnOdrDtlInfo().getRtnAmt())
                        .colReqDt(m.getColReqDt() == null ? "" : m.getColReqDt())
                        .storeId(m.getStoreId() == null ? "" : m.getStoreId())
                        .build())
                .collect(Collectors.toList());
        return GridResponse.toDTO(gridPage, gridTotal, gridRecords, gridRows);
    }

    /*
      수거지시 저장
*/
    @Transactional
    public void instColOdr(String userId, InstColOdrRequest instColOdrRequest) throws Exception {
        try {

            List<RtnOdrDtlPtclEntity> gridInsertData = instColOdrRequest.toCodeEntities(instColOdrRequest.getGridInsertData());
            List<RtnOdrBaseInfoEntity> jobList = colOdrMapper.selectPickJobDataList(instColOdrRequest.getBrandId(), gridInsertData);

            String whsId = "";
            String location = "";
            String rtnWhsId = "";
            String rtnLocation = "";
            int itemQty = 0;
            long colTotalAmt = 0;
            int colQty = 0;
            String colCmdUnqNo = "";
            String colPickUnqNo = "";

            ColOdrBaseEntity colOdrBaseEntity = new ColOdrBaseEntity();
            List<ColOdrDtlPtclEntity> colDtlList = new ArrayList<ColOdrDtlPtclEntity>();

            PickInfoMgntEntity pickInfoMgntEntity = new PickInfoMgntEntity();
            List<PickDtlPtclEntity> pickDtlList = new ArrayList<PickDtlPtclEntity>();

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

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

                    if (entity.getRtnPodrUnqNo().equals(reqEntity.getRtnPodrUnqNo()) && entity.getRtnOdrDtlInfo().getRtnPodrDtlNo().equals(reqEntity.getRtnPodrDtlNo())) {
                        if (reqEntity.getColQty() > entity.getRtnOdrDtlInfo().getRtnOdrQty()) {
                            // 반품발주수량보다 수거수량이 많을수 없습니다.
                            throw new GlobalException(SystemMessageCode.ERR_POPICKQTY);
                        }

                        colQty = reqEntity.getColQty();

                        break;
                    }
                }

                if (rtnWhsId.equals(entity.getRtnWhsId()) && rtnLocation.equals(entity.getRtnLocation()) && whsId.equals(entity.getWhsId()) && location.equals(entity.getLocation())) {
                    // 추가 작업
                    itemQty = itemQty + 1;
                    colTotalAmt = colTotalAmt + (entity.getRtnOdrDtlInfo().getUnitAmt() * colQty);
                    colOdrBaseEntity.setItemQty(itemQty);
                    colOdrBaseEntity.setColTotalAmt(colTotalAmt);
                    pickInfoMgntEntity.setColTotAmt(colTotalAmt);

                    //수거서 상세 정보
                    int dtlNo = itemQty * 10;

                    ColOdrDtlPtclEntity colDtlEntity = new ColOdrDtlPtclEntity();
                    colDtlEntity.setColCmdUnqNo(colCmdUnqNo);
                    colDtlEntity.setColCmdDtlNo(Integer.toString(dtlNo));
                    colDtlEntity.setItemId(entity.getRtnOdrDtlInfo().getItemId());
                    colDtlEntity.setItemNm(entity.getRtnOdrDtlInfo().getItemNm());
                    colDtlEntity.setUnitAmt(entity.getRtnOdrDtlInfo().getUnitAmt());
                    colDtlEntity.setColQty(colQty);
                    colDtlEntity.setColAmt(colQty * entity.getRtnOdrDtlInfo().getUnitAmt());
                    colDtlEntity.setRtnQty(entity.getRtnOdrDtlInfo().getRtnOdrQty());
                    colDtlEntity.setRtnAmt(entity.getRtnOdrDtlInfo().getRtnOdrAmt());
                    colDtlEntity.setRtnRsnDvsn(entity.getRtnOdrDtlInfo().getRtnRsnDvsn());
                    colDtlEntity.setRtnRsn(entity.getRtnOdrDtlInfo().getRtnRsn());
                    colDtlEntity.setRtnPodrUnqNo(entity.getRtnPodrUnqNo());
                    colDtlEntity.setRtnPodrDtlNo(entity.getRtnOdrDtlInfo().getRtnPodrDtlNo());
                    colDtlEntity.setRtnReqUnqNo(entity.getRtnOdrDtlInfo().getRtnReqUnqNo());
                    colDtlEntity.setRtnReqDtlNo(entity.getRtnOdrDtlInfo().getRtnReqDtlNo());

                    colDtlList.add(colDtlEntity);

                    PickDtlPtclEntity pickDtlEntity = new PickDtlPtclEntity();
                    pickDtlEntity.setColPickUnqNo(colPickUnqNo);

                    pickDtlEntity.setColPickDtlNo(Integer.toString(dtlNo));
                    pickDtlEntity.setRtnPodrUnqNo(entity.getRtnPodrUnqNo());
                    pickDtlEntity.setRtnPodrDtlNo(entity.getRtnOdrDtlInfo().getRtnPodrDtlNo());
                    pickDtlEntity.setRtnReqUnqNo(entity.getRtnOdrDtlInfo().getRtnReqUnqNo());
                    pickDtlEntity.setRtnReqDtlNo(entity.getRtnOdrDtlInfo().getRtnReqDtlNo());
                    pickDtlEntity.setColCmdUnqNo(colCmdUnqNo);
                    pickDtlEntity.setColCmdDtlNo(Integer.toString(dtlNo));
                    pickDtlEntity.setItemId(entity.getRtnOdrDtlInfo().getItemId());
                    pickDtlEntity.setItemNm(entity.getRtnOdrDtlInfo().getItemNm());
                    pickDtlEntity.setUnit(entity.getRtnOdrDtlInfo().getUnit());
                    pickDtlEntity.setUnitAmt(entity.getRtnOdrDtlInfo().getUnitAmt());
                    pickDtlEntity.setRodrQty(entity.getRtnOdrDtlInfo().getRtnOdrQty());
                    pickDtlEntity.setColReqQty(colQty);
                    pickDtlEntity.setColReqAmt(colQty * entity.getRtnOdrDtlInfo().getUnitAmt());

                    pickDtlList.add(pickDtlEntity);

                } else {
                    // 신규로 출하건 생성함  //select fn_get_dealno(16, '') as col_cmd_unq_no
                    if (colDtlList.size() > 0) {

                        colOdrMapper.insertColOdrBase(userId,colOdrBaseEntity);
                        colOdrMapper.insertColOdrDtl(userId,colDtlList);
                        colOdrMapper.insertPickMgntBase(userId,pickInfoMgntEntity);
                        colOdrMapper.insertPickDtlPtcl(userId,pickDtlList);

                        itemQty = 0;
                        colTotalAmt = 0;
                    }
                    itemQty = 1;
                    colTotalAmt = entity.getRtnOdrDtlInfo().getUnitAmt() * colQty;

                    whsId = entity.getWhsId();
                    location = entity.getLocation();
                    rtnWhsId = entity.getRtnWhsId();
                    rtnLocation = entity.getRtnLocation();

                    colCmdUnqNo = fnGetDealNo(20, "");  // 출하지시번호
                    colPickUnqNo = fnGetDealNo(15, ""); // 납품서번호

                    // 수거지시
                    colOdrBaseEntity = new ColOdrBaseEntity();
                    colDtlList = new ArrayList<ColOdrDtlPtclEntity>();
                    ColOdrDtlPtclEntity colDtlEntity = new ColOdrDtlPtclEntity();

                    //납품서정보
                    pickInfoMgntEntity= new PickInfoMgntEntity();
                    pickDtlList = new ArrayList<PickDtlPtclEntity>();
                    PickDtlPtclEntity pickDtlEntity = new PickDtlPtclEntity();

                    colOdrBaseEntity.setColCmdUnqNo(colCmdUnqNo);
                    colOdrBaseEntity.setBrandId(entity.getBrandId());
                    colOdrBaseEntity.setWhsId(entity.getWhsId());
                    colOdrBaseEntity.setLocation(entity.getLocation());
                    colOdrBaseEntity.setStoreId(entity.getStoreId());
                    colOdrBaseEntity.setColPickUnqNo(colPickUnqNo);
                    colOdrBaseEntity.setItemQty(itemQty);
                    colOdrBaseEntity.setColTotalAmt(colTotalAmt);
                    colOdrBaseEntity.setColReqDt(instColOdrRequest.getColSchDt().replaceAll("\\.",""));
                    colOdrBaseEntity.setColDvsn(entity.getColDvsn());
                    colOdrBaseEntity.setColCmdStCd("COL1");
                    colOdrBaseEntity.setColReqMgrNm(entity.getRtnMgrNm());
                    colOdrBaseEntity.setColReqMgrId(entity.getRtnMgrId());
                    colOdrBaseEntity.setColDt(null);
                    colOdrBaseEntity.setColCnfmNm(null);
                    colOdrBaseEntity.setColCnfmId(null);
                    colOdrBaseEntity.setColMgrNm(instColOdrRequest.getPickMgrNm());
                    colOdrBaseEntity.setColMgrTelNo(instColOdrRequest.getPickMgrTelNo().replaceAll("-",""));
                    colOdrBaseEntity.setColMgrEmal(null);
                    colOdrBaseEntity.setColMgrMblNo(null);
                    colOdrBaseEntity.setRtnWhsId(entity.getRtnWhsId());
                    colOdrBaseEntity.setRtnLocation(entity.getRtnLocation());
                    colOdrBaseEntity.setSpplyId(entity.getSpplyId());
                    colOdrBaseEntity.setSpplyNm(entity.getSpplyNm());

                    colDtlEntity.setColCmdUnqNo(colCmdUnqNo);
                    colDtlEntity.setColCmdDtlNo("10");
                    colDtlEntity.setItemId(entity.getRtnOdrDtlInfo().getItemId());
                    colDtlEntity.setItemNm(entity.getRtnOdrDtlInfo().getItemNm());
                    colDtlEntity.setUnitAmt(entity.getRtnOdrDtlInfo().getUnitAmt());
                    colDtlEntity.setColQty(colQty);
                    colDtlEntity.setColAmt(colQty * entity.getRtnOdrDtlInfo().getUnitAmt());
                    colDtlEntity.setRtnQty(entity.getRtnOdrDtlInfo().getRtnOdrQty());
                    colDtlEntity.setRtnAmt(entity.getRtnOdrDtlInfo().getRtnOdrAmt());
                    colDtlEntity.setRtnRsnDvsn(entity.getRtnOdrDtlInfo().getRtnRsnDvsn());
                    colDtlEntity.setRtnRsn(entity.getRtnOdrDtlInfo().getRtnRsn());
                    colDtlEntity.setRtnPodrUnqNo(entity.getRtnPodrUnqNo());
                    colDtlEntity.setRtnPodrDtlNo(entity.getRtnOdrDtlInfo().getRtnPodrDtlNo());
                    colDtlEntity.setRtnReqUnqNo(entity.getRtnOdrDtlInfo().getRtnReqUnqNo());
                    colDtlEntity.setRtnReqDtlNo(entity.getRtnOdrDtlInfo().getRtnReqDtlNo());
                    colDtlList.add(colDtlEntity);

                    pickInfoMgntEntity.setColPickUnqNo(colPickUnqNo);
                    pickInfoMgntEntity.setSpplyId(entity.getSpplyId());
                    pickInfoMgntEntity.setSpplyNm(entity.getSpplyNm());
                    pickInfoMgntEntity.setStoreId(entity.getStoreId());
                    pickInfoMgntEntity.setColTotAmt(colTotalAmt);
                    pickInfoMgntEntity.setColDvsn(entity.getColDvsn());
                    pickInfoMgntEntity.setPickMgrNm(instColOdrRequest.getPickMgrNm());
                    pickInfoMgntEntity.setPickMgrTelNo(instColOdrRequest.getPickMgrTelNo().replaceAll("-",""));
                    pickInfoMgntEntity.setPndrTelNo(entity.getPickTelNo().replaceAll("-",""));
                    pickInfoMgntEntity.setPickStCd("PICK0");
                    pickInfoMgntEntity.setColReqDt(instColOdrRequest.getColSchDt().replaceAll("\\.",""));
                    pickInfoMgntEntity.setColSchDt(instColOdrRequest.getColSchDt().replaceAll("\\.",""));
                    pickInfoMgntEntity.setColCmpltDt(null);
                    pickInfoMgntEntity.setWhsId(entity.getRtnWhsId());
                    pickInfoMgntEntity.setLocation(entity.getRtnLocation());
                    //pickInfoMgntEntity.setColDvsn(entity.getColDvsn());
                    pickInfoMgntEntity.setWhsDvsn("C001".equals(entity.getColDvsn()) ? "W02" : "W01");  // 본사엣 수거면 매장,,, 공급사에서 수거면 본사
                    pickInfoMgntEntity.setBrandId(entity.getBrandId());
                    pickInfoMgntEntity.setColDesc(null);



                    pickDtlEntity.setColPickUnqNo(colPickUnqNo);

                    pickDtlEntity.setColPickDtlNo("10");
                    pickDtlEntity.setRtnPodrUnqNo(entity.getRtnPodrUnqNo());
                    pickDtlEntity.setRtnPodrDtlNo(entity.getRtnOdrDtlInfo().getRtnPodrDtlNo());
                    pickDtlEntity.setRtnReqUnqNo(entity.getRtnOdrDtlInfo().getRtnReqUnqNo());
                    pickDtlEntity.setRtnReqDtlNo(entity.getRtnOdrDtlInfo().getRtnReqDtlNo());
                    pickDtlEntity.setColCmdUnqNo(colCmdUnqNo);
                    pickDtlEntity.setColCmdDtlNo("10");
                    pickDtlEntity.setItemId(entity.getRtnOdrDtlInfo().getItemId());
                    pickDtlEntity.setItemNm(entity.getRtnOdrDtlInfo().getItemNm());
                    pickDtlEntity.setUnit(entity.getRtnOdrDtlInfo().getUnit());
                    pickDtlEntity.setUnitAmt(entity.getRtnOdrDtlInfo().getUnitAmt());
                    pickDtlEntity.setRodrQty(entity.getRtnOdrDtlInfo().getRtnOdrQty());
                    pickDtlEntity.setColReqQty(colQty);
                    pickDtlEntity.setColReqAmt(colQty * entity.getRtnOdrDtlInfo().getUnitAmt());

                    pickDtlList.add(pickDtlEntity);
                }

                // 마지막 부분일 경우 
                if (i == jobList.size() - 1) {
                    if (colDtlList.size() > 0) {
                        colOdrMapper.insertColOdrBase(userId,colOdrBaseEntity);
                        colOdrMapper.insertColOdrDtl(userId,colDtlList);
                        colOdrMapper.insertPickMgntBase(userId,pickInfoMgntEntity);
                        colOdrMapper.insertPickDtlPtcl(userId,pickDtlList);
                    }
                }

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

                for (int poi = 0; poi < gridInsertData.size(); poi++) {
                    gridInsertData.get(poi).setRodrDtlStCd("ROD3");
                }
                rtnOdrMapper.updateChangeMultiRodrDtlStCd(userId, gridInsertData);

                // 반품발주 헤더 상태 처리  updateChgMultiPodrStCd
                String rtnPodrUnqNo = "";
                for (int k = 0; k < gridInsertData.size(); k++) {
                    if (!rtnPodrUnqNo.equals(gridInsertData.get(k).getRtnPodrUnqNo())) {
                        rtnPodrUnqNo = gridInsertData.get(k).getRtnPodrUnqNo();
                        String rtnOdrStCd = rtnOdrService.selectRtnOdrDtlStatusList(rtnPodrUnqNo);
                        rtnOdrMapper.updateChgRodrStCd(userId, rtnPodrUnqNo, rtnOdrStCd);
                    }
                }
            }


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

    /* 수거현황 */
    public GridResponse selectColSearchGridList(String sBrandId, String fromDt, String toDt, String sColDvsn, String sWhsId, String sRtnWhsId, String sColCmdDtlStCd,  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 = colOdrMapper.selectColGridCnt(sBrandId, fromDt, toDt, sColDvsn, sWhsId,  sRtnWhsId, sColCmdDtlStCd, sItemNm);
        int gridTotal = fnCalculateGridTotal(gridSize, gridRecords);
        List<ColOdrBaseEntity> entities = colOdrMapper.selectColGridList(sBrandId, fromDt, toDt, sColDvsn, sWhsId,  sRtnWhsId, sColCmdDtlStCd, sItemNm, gridRequest);
        List<Object> gridRows = entities.stream()
                .map(m -> ColSearchListResponse.builder()
                        .viewCd("R")
                        .brandId(m.getBrandId() == null ? "" : m.getBrandId())
                        .brandNm(m.getBrandNm() == null ? "" : m.getBrandNm())
                        .colCmdUnqNo(m.getColCmdUnqNo() == null ? "" : m.getColCmdUnqNo())
                        .colCmdDtlNo(m.getColDtlInfo() == null ? "" : m.getColDtlInfo().getColCmdDtlNo() == null ? "" :   m.getColDtlInfo().getColCmdDtlNo())
                        .rtnPodrUnqNo(m.getColDtlInfo() == null ? "" : m.getColDtlInfo().getRtnPodrUnqNo() == null ? "" :   m.getColDtlInfo().getRtnPodrUnqNo())
                        .rtnPodrDtlNo(m.getColDtlInfo() == null ? "" : m.getColDtlInfo().getRtnPodrDtlNo() == null ? "" :   m.getColDtlInfo().getRtnPodrDtlNo())
                        .colCmdDtlStCd(m.getColDtlInfo() == null ? "" : m.getColDtlInfo().getColCmdDtlStCd() == null ? "" :   m.getColDtlInfo().getColCmdDtlStCd())
                        .colCmdDtlStNm(m.getColDtlInfo() == null ? "" : m.getColDtlInfo().getColCmdDtlStNm() == null ? "" :   m.getColDtlInfo().getColCmdDtlStNm())
                        .itemId(m.getColDtlInfo() == null ? "" : m.getColDtlInfo().getItemId() == null ? "" :   m.getColDtlInfo().getItemId())
                        .itemNm(m.getColDtlInfo() == null ? "" : m.getColDtlInfo().getItemNm() == null ? "" :   m.getColDtlInfo().getItemNm())
                        .rtnWhsId(m.getRtnWhsId() == null ? "" : m.getRtnWhsId())
                        .rtnLocation(m.getRtnLocation() == null ? "" : m.getRtnLocation())
                        .rtnWhsNm(m.getRtnWhsNm() == null ? "" : m.getRtnWhsNm())
                        .colDvsn(m.getColDvsn() == null ? "" : m.getColDvsn())
                        .colDvsnNm(m.getColDvsnNm() == null ? "" : m.getColDvsnNm())
                        .whsId(m.getWhsId() == null ? "" : m.getWhsId())
                        .whsNm(m.getWhsNm() == null ? "" : m.getWhsNm())
                        .rtnQty(m.getColDtlInfo() == null ? 0 : m.getColDtlInfo().getRtnQty() == null ? 0 :   m.getColDtlInfo().getRtnQty())
                        .colQty(m.getColDtlInfo() == null ? 0 : m.getColDtlInfo().getColQty() == null ? 0 :   m.getColDtlInfo().getColQty())
                        .colAmt(m.getColDtlInfo() == null ? 0 : m.getColDtlInfo().getColAmt() == null ? 0 :   m.getColDtlInfo().getColAmt())
                        .colDt(m.getColDt() == null ? "" : m.getColDt())
                        .colCnfmNm(m.getColCnfmNm() == null ? "" : m.getColCnfmNm())
                        .colPickUnqNo(m.getColPickUnqNo() == null ? "" : m.getColPickUnqNo())
                        .build())
                .collect(Collectors.toList());
        return GridResponse.toDTO(gridPage, gridTotal, gridRecords, gridRows);
    }

    /* 수거서 정보 */
    public ColInfoResponse selectPickInfo(String brandId, String colPickUnqNo) throws Exception {

        PickInfoMgntEntity entity = colOdrMapper.selectPickInfo(brandId, colPickUnqNo);
        List<PickDtlPtclEntity> dtlEntity = colOdrMapper.selectPickDtlPtcl(brandId, colPickUnqNo);


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

        if ("C001".equals(entity.getColDvsn())) {   // 본사수거
            //브랜드정보 수거
            entity.setColBsnsRegno(brandEntity.getBsnsRegNo());
            entity.setColNm(brandEntity.getBrandNm());
            entity.setColOwnerNm(brandEntity.getOwnerNm());
            entity.setColAddr(brandEntity.getAddr1() + " " + brandEntity.getAddr2());

        } else {
            //공급사 수거
            SpplyEntity dlv_spplyEntity = supplyMapper.selectSpplyInfo(brandId, entity.getSpplyId());
            entity.setColBsnsRegno(dlv_spplyEntity.getBsnsRegNo());
            entity.setColNm(dlv_spplyEntity.getSpplyNm());
            entity.setColOwnerNm(dlv_spplyEntity.getOwnerNm());
            entity.setColAddr(dlv_spplyEntity.getAddr1() + " " + dlv_spplyEntity.getAddr2());
        }


        //반품처 정보  -- 수거장소가 매장
        if ("W01".equals(entity.getWhsDvsn())) {
            //납품창고 본사
            entity.setRtnBsnsRegno(brandEntity.getBsnsRegNo());
            entity.setRtnNm(brandEntity.getBrandNm());
            entity.setRtnOwnerNm(brandEntity.getOwnerNm());
            entity.setRtnAddr(brandEntity.getAddr1() + " " + brandEntity.getAddr2());
        } else {
            //납품창고 매장
            StoreBaseInfoEntity whs_storeBaseInfoEntity = storeBaseInfoMapper.selectStoreInfo(brandId, entity.getStoreId());
            entity.setRtnBsnsRegno(whs_storeBaseInfoEntity.getBsnsRegNo());
            entity.setRtnNm(whs_storeBaseInfoEntity.getStoreNm());
            entity.setRtnOwnerNm(whs_storeBaseInfoEntity.getOwnerNm());
            entity.setRtnAddr(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 ColInfoResponse.toDTO(entity, dtlEntity, logFileList);
    }


    /*
     공급사 수거대상 그리드 리스트 조회
*/
    public GridResponse selectSpplyTargetRtnGridList(String sBrandId, String fromDt, String toDt, String sSpplyId, String sRtnWhsId, 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 = colOdrMapper.selectColSpplyTargetRtnGridCnt(sBrandId,fromDt, toDt,sSpplyId,  sRtnWhsId, sItemNm);
        int gridTotal = fnCalculateGridTotal(gridSize, gridRecords);
        List<RtnOdrBaseInfoEntity> entities = colOdrMapper.selectColSpplyTargetRtnGridList(sBrandId,fromDt, toDt,sSpplyId,  sRtnWhsId, sItemNm, gridRequest);
        List<Object> gridRows = entities.stream()
                .map(m -> SpplyTargerRtnSearchListResponse.builder()
                        .viewCd("R")
                        .brandId(m.getBrandId() == null ? "" : m.getBrandId())
                        .brandNm(m.getBrandNm() == null ? "" : m.getBrandNm())
                        .rtnPodrUnqNo(m.getRtnPodrUnqNo() == null ? "" : m.getRtnPodrUnqNo())
                        .rtnPodrDtlNo(m.getRtnOdrDtlInfo() == null ? "" : m.getRtnOdrDtlInfo().getRtnPodrDtlNo() == null ? "" : m.getRtnOdrDtlInfo().getRtnPodrDtlNo())
                        .itemId(m.getRtnOdrDtlInfo() == null ? "" : m.getRtnOdrDtlInfo().getItemId() == null ? "" : m.getRtnOdrDtlInfo().getItemId())
                        .itemNm(m.getRtnOdrDtlInfo() == null ? "" : m.getRtnOdrDtlInfo().getItemNm() == null ? "" : m.getRtnOdrDtlInfo().getItemNm())
                        .rtnWhsId(m.getRtnWhsId() == null ? "" : m.getRtnWhsId())
                        .rtnWhsNm(m.getRtnWhsNm() == null ? "" : m.getRtnWhsNm() + " - " + m.getRtnLocationNm())
                        .rtnLocation(m.getRtnLocation() == null ? "" : m.getRtnLocation())
                        .unitAmt(m.getRtnOdrDtlInfo() == null ? 0 : m.getRtnOdrDtlInfo().getUnitAmt() == null ? 0 : m.getRtnOdrDtlInfo().getUnitAmt())
                        .rtnOdrQty(m.getRtnOdrDtlInfo() == null ? 0 : m.getRtnOdrDtlInfo().getRtnOdrQty() == null ? 0 : m.getRtnOdrDtlInfo().getRtnOdrQty())
                        .rtnOdrAmt(m.getRtnOdrDtlInfo() == null ? 0 : m.getRtnOdrDtlInfo().getRtnOdrAmt() == null ? 0 : m.getRtnOdrDtlInfo().getRtnOdrAmt())
                        .colReqDt(m.getColReqDt() == null ? "" : m.getColReqDt())
                        .build())
                .collect(Collectors.toList());
        return GridResponse.toDTO(gridPage, gridTotal, gridRecords, gridRows);
    }


    /* 공급사 납품서 생성 초기 정보*/
    public SpplyPickInitResponse selectSpplyShmtOdrInfo(String brandId, String spplyId, String rtnPodrUnqNo) throws Exception {
        RtnOdrBaseInfoEntity entity = colOdrMapper.selectSpplyColOdrInfo(brandId, spplyId, rtnPodrUnqNo);
        List<RtnOdrDtlPtclEntity> dtlEntity = colOdrMapper.selectSpplyColRtnList(rtnPodrUnqNo);

        return SpplyPickInitResponse.toDTO(entity, dtlEntity);
    }

    /* 공급사 수거서 생성 저장 */
    @Transactional
    public void saveSpplyPick(String userId, SaveSpplyPickRequest saveSpplyPickRequest) throws Exception {
        try {

            List<RtnOdrDtlPtclEntity> gridInsertData = saveSpplyPickRequest.toCodeEntities(saveSpplyPickRequest.getGridInsertData());
            List<RtnOdrBaseInfoEntity> jobList = colOdrMapper.selectPickJobDataList(saveSpplyPickRequest.getBrandId(), gridInsertData);
            long colTotalAmt = 0;
            int colQty = 0;
            String colPickUnqNo = "";

            PickInfoMgntEntity pickInfoMgntEntity = new PickInfoMgntEntity();
            List<PickDtlPtclEntity> pickDtlList = new ArrayList<PickDtlPtclEntity>();


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

                for (int j = 0; j < gridInsertData.size(); j++) {
                    RtnOdrDtlPtclEntity reqEntity = gridInsertData.get(j);
                    if (entity.getRtnPodrUnqNo().equals(reqEntity.getRtnPodrUnqNo()) && entity.getRtnOdrDtlInfo().getRtnPodrDtlNo().equals(reqEntity.getRtnPodrDtlNo())) {

                        if (reqEntity.getColQty() > entity.getRtnOdrDtlInfo().getRtnOdrQty()) {
                            // 반품발주수량보다 수거수량이 많을수 없습니다.
                            throw new GlobalException(SystemMessageCode.ERR_POPICKQTY);
                        }
                        colQty = reqEntity.getColQty();
                        break;
                    }
                }

                colTotalAmt = colTotalAmt + (entity.getRtnOdrDtlInfo().getUnitAmt() * colQty);
                if (i == 0 ) {
                    colPickUnqNo =  fnGetDealNo(15, ""); // 수거서번호

                    pickInfoMgntEntity.setColPickUnqNo(colPickUnqNo);
                    pickInfoMgntEntity.setSpplyId(entity.getSpplyId());
                    pickInfoMgntEntity.setSpplyNm(entity.getSpplyNm());
                    pickInfoMgntEntity.setStoreId(entity.getStoreId());
                    pickInfoMgntEntity.setPickMgrNm(saveSpplyPickRequest.getPickMgrNm());
                    pickInfoMgntEntity.setPickMgrTelNo(saveSpplyPickRequest.getPickMgrTelNo().replaceAll("-",""));
                    pickInfoMgntEntity.setPndrTelNo(entity.getPickTelNo().replaceAll("-",""));
                    pickInfoMgntEntity.setPickStCd("PICK0");
                    pickInfoMgntEntity.setColReqDt(saveSpplyPickRequest.getColSchDt().replaceAll("\\.",""));
                    pickInfoMgntEntity.setColSchDt(saveSpplyPickRequest.getColSchDt().replaceAll("\\.",""));
                    pickInfoMgntEntity.setColCmpltDt(null);
                    pickInfoMgntEntity.setWhsId(entity.getRtnWhsId());
                    pickInfoMgntEntity.setLocation(entity.getRtnLocation());
                    pickInfoMgntEntity.setColDvsn(entity.getColDvsn());
                    pickInfoMgntEntity.setWhsDvsn("C001".equals(entity.getColDvsn()) ? "W02" : "W01");  // 본사엣 수거면 매장,,, 공급사에서 수거면 본사
                    pickInfoMgntEntity.setBrandId(entity.getBrandId());
                    pickInfoMgntEntity.setColDesc(null);

                    PickDtlPtclEntity pickDtlEntity = new PickDtlPtclEntity();
                    pickDtlEntity.setColPickUnqNo(colPickUnqNo);

                    pickDtlEntity.setColPickDtlNo("10");
                    pickDtlEntity.setRtnPodrUnqNo(entity.getRtnPodrUnqNo());
                    pickDtlEntity.setRtnPodrDtlNo(entity.getRtnOdrDtlInfo().getRtnPodrDtlNo());
                    pickDtlEntity.setRtnReqUnqNo(entity.getRtnOdrDtlInfo().getRtnReqUnqNo());
                    pickDtlEntity.setRtnReqDtlNo(entity.getRtnOdrDtlInfo().getRtnReqDtlNo());
                    pickDtlEntity.setColCmdUnqNo(null);
                    pickDtlEntity.setColCmdDtlNo(null);
                    pickDtlEntity.setItemId(entity.getRtnOdrDtlInfo().getItemId());
                    pickDtlEntity.setItemNm(entity.getRtnOdrDtlInfo().getItemNm());
                    pickDtlEntity.setUnit(entity.getRtnOdrDtlInfo().getUnit());
                    pickDtlEntity.setUnitAmt(entity.getRtnOdrDtlInfo().getUnitAmt());
                    pickDtlEntity.setRodrQty(entity.getRtnOdrDtlInfo().getRtnOdrQty());
                    pickDtlEntity.setColReqQty(colQty);
                    colTotalAmt = colQty * entity.getRtnOdrDtlInfo().getUnitAmt();
                    pickDtlEntity.setColReqAmt(colTotalAmt);

                    pickDtlList.add(pickDtlEntity);
                } else {

                    int dtlNo = (i + 1) * 10;

                    PickDtlPtclEntity pickDtlEntity = new PickDtlPtclEntity();
                    pickDtlEntity.setColPickUnqNo(colPickUnqNo);

                    pickDtlEntity.setColPickDtlNo(Integer.toString(dtlNo));
                    pickDtlEntity.setRtnPodrUnqNo(entity.getRtnPodrUnqNo());
                    pickDtlEntity.setRtnPodrDtlNo(entity.getRtnOdrDtlInfo().getRtnPodrDtlNo());
                    pickDtlEntity.setRtnReqUnqNo(entity.getRtnOdrDtlInfo().getRtnReqUnqNo());
                    pickDtlEntity.setRtnReqDtlNo(entity.getRtnOdrDtlInfo().getRtnReqDtlNo());
                    pickDtlEntity.setColCmdUnqNo(null);
                    pickDtlEntity.setColCmdDtlNo(null);
                    pickDtlEntity.setItemId(entity.getRtnOdrDtlInfo().getItemId());
                    pickDtlEntity.setItemNm(entity.getRtnOdrDtlInfo().getItemNm());
                    pickDtlEntity.setUnit(entity.getRtnOdrDtlInfo().getUnit());
                    pickDtlEntity.setUnitAmt(entity.getRtnOdrDtlInfo().getUnitAmt());
                    pickDtlEntity.setRodrQty(entity.getRtnOdrDtlInfo().getRtnOdrQty());
                    pickDtlEntity.setColReqQty(colQty);
                    pickDtlEntity.setColReqAmt(colQty * entity.getRtnOdrDtlInfo().getUnitAmt());
                    pickDtlList.add(pickDtlEntity);
                }

            }

            pickInfoMgntEntity.setColTotAmt(colTotalAmt);
            colOdrMapper.insertPickMgntBase(userId, pickInfoMgntEntity);
            colOdrMapper.insertPickDtlPtcl(userId, pickDtlList);



            for (int poi = 0; poi < gridInsertData.size(); poi++) {
                gridInsertData.get(poi).setRodrDtlStCd("ROD3");
            }
            rtnOdrMapper.updateChangeMultiRodrDtlStCd(userId, gridInsertData);

            // 반품발주 헤더 상태 처리  updateChgMultiPodrStCd
            String rtnPodrUnqNo = "";
            for (int k = 0; k < gridInsertData.size(); k++) {
                if (!rtnPodrUnqNo.equals(gridInsertData.get(k).getRtnPodrUnqNo())) {
                    rtnPodrUnqNo = gridInsertData.get(k).getRtnPodrUnqNo();
                    String rtnOdrStCd = rtnOdrService.selectRtnOdrDtlStatusList(rtnPodrUnqNo);
                    rtnOdrMapper.updateChgRodrStCd(userId, rtnPodrUnqNo, rtnOdrStCd);
                }
            }

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


    /*
      공급사  - 수거서 현황 그리드 리스트 조회
 */
    public GridResponse selectSpplyPickGridList(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 = colOdrMapper.selectColSpplyPickGridCnt(sBrandId,  fromDt, toDt, sSpplyId, sWhsId, sItemNm);
        int gridTotal = fnCalculateGridTotal(gridSize, gridRecords);
        List<PickInfoMgntEntity> entities = colOdrMapper.selectColSpplyPickGridList(sBrandId, fromDt, toDt, sSpplyId, sWhsId, sItemNm, gridRequest);
        List<Object> gridRows = entities.stream()
                .map(m -> PickDtlSearchListResponse.builder()
                        .viewCd("R")
                        .brandId(m.getBrandId() == null ? "" : m.getBrandId())
                        .brandNm(m.getBrandNm() == null ? "" : m.getBrandNm())
                        .colPickUnqNo(m.getColPickUnqNo() == null ? "" : m.getColPickUnqNo())
                        .pickStCd(m.getPickStCd() == null ? "" : m.getPickStCd())
                        .pickStNm(m.getPickStNm() == null ? "" : m.getPickStNm())
                        .colRegDt(m.getColRegDt() == null ? "" : m.getColRegDt())
                        .colReqDt(m.getColReqDt() == null ? "" : m.getColReqDt())
                        .colSchDt(m.getColSchDt() == null ? "" : m.getColSchDt())
                        .colCmpltDt(m.getColCmpltDt() == null ? "" : m.getColCmpltDt())
                        .itemId(m.getPickDtlInfo() == null ? "" : m.getPickDtlInfo().getItemId() == null ? "" :  m.getPickDtlInfo().getItemId())
                        .itemNm(m.getPickDtlInfo() == null ? "" : m.getPickDtlInfo().getItemNm() == null ? "" :  m.getPickDtlInfo().getItemNm())
                        .colReqQty(m.getPickDtlInfo() == null ? 0 : m.getPickDtlInfo().getColReqQty() == null ? 0 :  m.getPickDtlInfo().getColReqQty())
                        .rtnRsnDvsn(m.getPickDtlInfo() == null ? "" : m.getPickDtlInfo().getRtnRsnDvsn() == null ? "" :  m.getPickDtlInfo().getRtnRsnDvsn())
                        .rtnRsnDvsnNm(m.getPickDtlInfo() == null ? "" : m.getPickDtlInfo().getRtnRsnDvsnNm() == null ? "" :  m.getPickDtlInfo().getRtnRsnDvsnNm())
                        .unitAmt(m.getPickDtlInfo() == null ? 0 : m.getPickDtlInfo().getUnitAmt() == null ? 0 :  m.getPickDtlInfo().getUnitAmt())
                        .colReqAmt(m.getPickDtlInfo() == null ? 0 : m.getPickDtlInfo().getColReqAmt() == null ? 0 :  m.getPickDtlInfo().getColReqAmt())
                        .whsNm(m.getWhsNm() == null ? "" : m.getWhsNm() + " - " + m.getLocationNm())
                        .pickMgrNm(m.getPickMgrNm() == null ? "" : m.getPickMgrNm())
                        .pickMgrTelNo(m.getPickMgrTelNo() == null ? "" : m.getPickMgrTelNo())
                        .build())
                .collect(Collectors.toList());
        return GridResponse.toDTO(gridPage, gridTotal, gridRecords, gridRows);
    }

  /*
      반품처리 그리드 리스트 조회
 */
    public GridResponse selectRtnStockTargetList(String userId, String sBrandId, String sStoreId, String sColPickUnqNo ,String fromDt, String toDt, String sRtnWhsId, String sSpplyId, String sWhsId, 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(sStoreId)) {
                throw new GlobalException(SystemMessageCode.ERR_NONSTOREID);
            }
        }

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

        int gridRecords = colOdrMapper.selectColRtnInstGridCnt(sBrandId, sStoreId,sColPickUnqNo, fromDt, toDt, sSpplyId, sRtnWhsId,  sWhsId,  sItemNm);
        int gridTotal = fnCalculateGridTotal(gridSize, gridRecords);
        List<PickInfoMgntEntity> entities = colOdrMapper.selectColRtnInstGridList(sBrandId, sStoreId, sColPickUnqNo, fromDt, toDt, sSpplyId, sRtnWhsId, sWhsId, sItemNm, gridRequest);
        List<Object> gridRows = entities.stream()
                .map(m -> RtnStockTargetResponse.builder()
                        .viewCd("R")
                        .brandId(m.getBrandId() == null ? "" : m.getBrandId())
                        .brandNm(m.getBrandNm() == null ? "" : m.getBrandNm())
                        .storeId(m.getStoreId() == null ? "" : m.getStoreId())
                        .colPickUnqNo(m.getColPickUnqNo() == null ? "" : m.getColPickUnqNo())
                        .colPickDtlNo(m.getPickDtlInfo() == null ? "" : m.getPickDtlInfo().getColPickDtlNo() == null ? "" :m.getPickDtlInfo().getColPickDtlNo() )
                        .rtnPodrUnqNo(m.getPickDtlInfo() == null ? "" : m.getPickDtlInfo().getRtnPodrUnqNo() == null ? "" :m.getPickDtlInfo().getRtnPodrUnqNo() )
                        .rtnPodrDtlNo(m.getPickDtlInfo() == null ? "" : m.getPickDtlInfo().getRtnPodrDtlNo() == null ? "" :m.getPickDtlInfo().getRtnPodrDtlNo() )
                        .itemId(m.getPickDtlInfo() == null ? "" : m.getPickDtlInfo().getItemId() == null ? "" :m.getPickDtlInfo().getItemId() )
                        .itemNm(m.getPickDtlInfo() == null ? "" : m.getPickDtlInfo().getItemNm() == null ? "" :m.getPickDtlInfo().getItemNm() )
                        //.colQty(m.getPickDtlInfo() == null ? 0 : m.getPickDtlInfo().getColQty() == null ? 0 :m.getPickDtlInfo().getColQty() )
                        .colReqQty(m.getPickDtlInfo() == null ? 0 : m.getPickDtlInfo().getColReqQty() == null ? 0 :m.getPickDtlInfo().getColReqQty() )
                        .rodrQty(m.getPickDtlInfo() == null ? 0 : m.getPickDtlInfo().getRodrQty() == null ? 0 :m.getPickDtlInfo().getRodrQty() )
                        //.colAmt(m.getPickDtlInfo() == null ? 0 : m.getPickDtlInfo().getColAmt() == null ? 0 :m.getPickDtlInfo().getColAmt() )
                        .whsId(m.getWhsId() == null ? "" : m.getWhsId())
                        .location(m.getLocation() == null ? "" : m.getLocation())
                        .whsNm(m.getWhsNm() == null ? "" : m.getWhsNm() + " - " + m.getLocationNm())
                        .rtnWhsId(m.getRtnWhsId() == null ? "" : m.getRtnWhsId())
                        .rtnLocation(m.getRtnLocation() == null ? "" : m.getRtnLocation())
                        .rtnWhsNm(m.getRtnWhsNm() == null ? "" : m.getRtnWhsNm())
                        .colSchDt(m.getColReqDt() == null ? "" : m.getColReqDt())
                        .colSchDt(m.getColSchDt() == null ? "" : m.getColSchDt())
                        .pickMgrNm(m.getPickMgrNm() == null ? "" : m.getPickMgrNm())
                        .pickMgrTelNo(m.getPickMgrTelNo() == null ? "" : m.getPickMgrTelNo())
                        .spplyId(m.getSpplyId() == null ? "" : m.getSpplyId())
                        .spplyNm(m.getSpplyNm() == null ? "" : m.getSpplyNm())
                        .unitAmt((m.getPickDtlInfo() == null ? 0 : m.getPickDtlInfo().getUnitAmt() == null ? 0 : m.getPickDtlInfo().getUnitAmt()))
                        .colReqAmt(m.getPickDtlInfo() == null ? 0 : m.getPickDtlInfo().getColReqAmt() == null ? 0 : m.getPickDtlInfo().getColReqAmt())
                        .build())
                .collect(Collectors.toList());
        return GridResponse.toDTO(gridPage, gridTotal, gridRecords, gridRows);
    }





    /* 수거 처리 저장 */
    @Transactional
    public void saveRtnStockProc(String userId, SaveRtnStockProcRequest saveRtnStockProcRequest) throws Exception {
        try {
            List<RtnProcInfoPtclEntity> gridInsertData = saveRtnStockProcRequest.toCodeEntities(saveRtnStockProcRequest.getGridInsertData());
            List<RtnProcInfoPtclEntity> searchList = new ArrayList<RtnProcInfoPtclEntity>();
            if (gridInsertData.size() > 0) {
                for (int i = 0; i < gridInsertData.size(); i++) {
                    RtnProcInfoPtclEntity targetData = gridInsertData.get(i);
                    RtnProcInfoPtclEntity procData = new RtnProcInfoPtclEntity();
                    procData.setColPickUnqNo(targetData.getColPickUnqNo() + targetData.getColPickDtlNo());
                    searchList.add(procData);
                }

                String storeWhsUseYn = "Y";
                //로그인 사용자 정보
                UserMngEntity uEntity = userMngMapper.selectGroupUserInfo(userId);

                // 창고사용여부 값 가져오기
                if (!"".toString().equals(saveRtnStockProcRequest.getStoreId())) {
                    StoreBaseInfoEntity whsUseInfo = storeBaseInfoMapper.selectStoreLoanInfo(uEntity.getBrandId(), uEntity.getStoreId());
                    storeWhsUseYn = whsUseInfo.getWhsUseYn();
                }

                // 여신금액 합
                long acctbalAmt = 0 ;

                List<RtnProcInfoPtclEntity> rtnProcInfoPtclList = new ArrayList<RtnProcInfoPtclEntity>();
                List<StckMgntBaseInfoEntity> stckMgntBaseInfoList = new ArrayList<StckMgntBaseInfoEntity>();
                List<StckMgntDtlHistEntity> stckMgntDtlHistList= new ArrayList<StckMgntDtlHistEntity>();
                List<ColOdrDtlPtclEntity> colOdrDtlPtclList= new ArrayList<ColOdrDtlPtclEntity>();
                List<PickDtlPtclEntity> pickDtlPtclList= new ArrayList<PickDtlPtclEntity>();
                List<ColOdrBaseEntity> colOdrBaseList= new ArrayList<ColOdrBaseEntity>();
                List<PickInfoMgntEntity> pickInfoMgntList = new ArrayList<PickInfoMgntEntity>();

                // 반품처리를 위한 관련정보를 가져온다
                List<PickInfoMgntEntity> targetList = colOdrMapper.selectColRtnInstProcList(saveRtnStockProcRequest.getBrandId(), saveRtnStockProcRequest.getRtnWhsId(), searchList);

                //String loanMgntUnqNo = "";
                LoanMgntBaseInfoEntity loanInfo = null ;
                long loanAmt = 0 ; // 여신차감할 금액 (사용금액 - 여신차감금액,   잔액금액 - 여신차감금액)
                if (!"".toString().equals(saveRtnStockProcRequest.getStoreId())) {
                    loanInfo = loanStateMapper.selectLoanRtnDataInfo(saveRtnStockProcRequest.getStoreId());
                }



                for (int i = 0; i < gridInsertData.size(); i++) {
                    RtnProcInfoPtclEntity requestData = gridInsertData.get(i);

                    for (int j = 0; j < targetList.size(); j++) {
                        PickInfoMgntEntity targetData = targetList.get(j);

                        RtnProcInfoPtclEntity rtnProcInfoEntity = new RtnProcInfoPtclEntity();

                        if (requestData.getColPickUnqNo().equals(targetData.getColPickUnqNo()) && requestData.getColPickDtlNo().equals(targetData.getPickDtlInfo().getColPickDtlNo())) {

                            if (targetData.getColDvsn().equals("C001") && "".equals(saveRtnStockProcRequest.getStoreId())) {
                                throw new GlobalException(SystemMessageCode.ERR_NONSTOREID);
                            }

                            if (requestData.getColQty() > targetData.getPickDtlInfo().getColReqQty()) {
                                // 반품입고수량이 수거요청수량보다 클 수 없습니다.
                                throw new GlobalException(SystemMessageCode.ERR_NOTRTNQTY);
                            }

                            if (targetData.getColDvsn().equals("C001") && !saveRtnStockProcRequest.getWhsId().equals(targetData.getWhsId())) {
                                // 본사 수거이변서 입고창고가 상이하면 오류
                                throw new GlobalException(SystemMessageCode.ERR_NOTRTNINWHS);
                            }
                        }

                        // 반품처리  진행 데이타생성
                        if (requestData.getColPickUnqNo().equals(targetData.getColPickUnqNo()) && requestData.getColPickDtlNo().equals(targetData.getPickDtlInfo().getColPickDtlNo())) {
                            String rtnMgntUnqNo = fnGetDealNo(37, "");
                            rtnProcInfoEntity.setRtnMgntUnqNo(rtnMgntUnqNo);
                            rtnProcInfoEntity.setBrandId(saveRtnStockProcRequest.getBrandId());
                            rtnProcInfoEntity.setStoreId(saveRtnStockProcRequest.getStoreId());
                            rtnProcInfoEntity.setItemId(requestData.getItemId());
                            rtnProcInfoEntity.setItemNm(targetData.getPickDtlInfo().getItemNm());
                            rtnProcInfoEntity.setWhsId(saveRtnStockProcRequest.getRtnWhsId());
                            rtnProcInfoEntity.setLocation(targetData.getRtnLocation());
                            rtnProcInfoEntity.setUnit(targetData.getPickDtlInfo().getUnit());
                            rtnProcInfoEntity.setUnitAmt(targetData.getPickDtlInfo().getUnitAmt());
                            rtnProcInfoEntity.setRtnReqQty(targetData.getPickDtlInfo().getRtnReqQty());
                            rtnProcInfoEntity.setRtnOdrQty(targetData.getPickDtlInfo().getRodrQty());
                            rtnProcInfoEntity.setColReqQty(targetData.getPickDtlInfo().getColReqQty());
                            rtnProcInfoEntity.setColQty(requestData.getColQty());
                            rtnProcInfoEntity.setColReqDt(targetData.getColReqDt());
                            rtnProcInfoEntity.setColSchDt(targetData.getColSchDt());
                            rtnProcInfoEntity.setColCnfmNm(uEntity.getUserNm());
                            rtnProcInfoEntity.setColMgrTelNo(targetData.getPickMgrTelNo());
                            rtnProcInfoEntity.setColMgrNm(targetData.getPickMgrNm());
                            rtnProcInfoEntity.setColAmt(requestData.getColQty() * targetData.getPickDtlInfo().getUnitAmt());
                            rtnProcInfoEntity.setColAgrYn("Y");
                            // rtnProcInfoEntity.setColCnfmDocFileNo(saveRtnStockProcRequest.); 수거서 파일 첨부 제거
                            rtnProcInfoEntity.setSttlYn("N");
                            rtnProcInfoEntity.setSpplyId(targetData.getSpplyId());
                            rtnProcInfoEntity.setSpplyNm(targetData.getSpplyNm());
                            rtnProcInfoEntity.setColPickUnqNo(targetData.getColPickUnqNo());
                            rtnProcInfoEntity.setColPickDtlNo(targetData.getPickDtlInfo().getColPickDtlNo());
                            rtnProcInfoEntity.setColCmdUnqNo(targetData.getPickDtlInfo().getColCmdUnqNo());
                            rtnProcInfoEntity.setColCmdDtlNo(targetData.getPickDtlInfo().getColCmdDtlNo());
                            rtnProcInfoEntity.setRtnPodrUnqNo(targetData.getPickDtlInfo().getRtnPodrUnqNo());
                            rtnProcInfoEntity.setRtnPodrDtlNo(targetData.getPickDtlInfo().getRtnPodrDtlNo());
                            rtnProcInfoEntity.setRtnReqUnqNo(targetData.getPickDtlInfo().getRtnReqUnqNo());
                            rtnProcInfoEntity.setRtnReqDtlNo(targetData.getPickDtlInfo().getRtnReqDtlNo());
                            rtnProcInfoPtclList.add(rtnProcInfoEntity);

                            // 본사 수거 반품입고처리시
                            if (targetData.getColDvsn().equals("C001") && requestData.getColQty() > 0) {
                                //본사수거 .
                                // 1. 매장재고참감처리, 본사재고 증가, 2. 반품처리테이블 생성, 3. 수거서 업데이타, 4, 반품발주건 업데이트
                                // 매장재고 차감
                                if ("Y".toString().equals(storeWhsUseYn)) {
                                    StckMgntBaseInfoEntity stckWEntity = new StckMgntBaseInfoEntity();
                                    stckWEntity.setBrandId(saveRtnStockProcRequest.getBrandId());
                                    stckWEntity.setWhsId(saveRtnStockProcRequest.getRtnWhsId());
                                    stckWEntity.setLocation(targetData.getRtnLocation());
                                    stckWEntity.setItemId(requestData.getItemId());
                                    stckWEntity.setStckQty(requestData.getColQty() * (-1));
                                    stckWEntity.setUnit(targetData.getPickDtlInfo().getUnit());
                                    stckMgntBaseInfoList.add(stckWEntity);

                                    // 재고 이력정보 등록
                                    StckMgntDtlHistEntity stckWHist = new StckMgntDtlHistEntity();
                                    stckWHist.setStckMgntDtlNo(fnGetDealNo(37, ""));
                                    stckWHist.setBrandId(saveRtnStockProcRequest.getBrandId());
                                    stckWHist.setWhsId(saveRtnStockProcRequest.getRtnWhsId());
                                    stckWHist.setLocation(targetData.getRtnLocation());
                                    stckWHist.setItemId(requestData.getItemId());
                                    stckWHist.setItemNm(targetData.getPickDtlInfo().getItemNm());
                                    stckWHist.setInoutCd("OUT");
                                    stckWHist.setInoutQty(requestData.getColQty());
                                    stckWHist.setChgDvsn("ROUT");
                                    stckWHist.setRelationNo(rtnMgntUnqNo);
                                    stckMgntDtlHistList.add(stckWHist);
                                }

                                //본사재고 증가
                                StckMgntBaseInfoEntity stckW1Entity = new StckMgntBaseInfoEntity();
                                stckW1Entity.setBrandId(saveRtnStockProcRequest.getBrandId());
                                stckW1Entity.setWhsId(saveRtnStockProcRequest.getWhsId());
                                stckW1Entity.setLocation(targetData.getLocation());
                                stckW1Entity.setItemId(requestData.getItemId());
                                stckW1Entity.setStckQty(requestData.getColQty());
                                stckW1Entity.setUnit(targetData.getPickDtlInfo().getUnit());
                                stckMgntBaseInfoList.add(stckW1Entity);

                                // 재고 이력정보 등록
                                StckMgntDtlHistEntity stckW1Hist = new StckMgntDtlHistEntity();
                                stckW1Hist.setStckMgntDtlNo(fnGetDealNo(37, ""));
                                stckW1Hist.setBrandId(saveRtnStockProcRequest.getBrandId());
                                stckW1Hist.setWhsId(saveRtnStockProcRequest.getWhsId());
                                stckW1Hist.setLocation(targetData.getLocation());
                                stckW1Hist.setItemId(requestData.getItemId());
                                stckW1Hist.setItemNm(targetData.getPickDtlInfo().getItemNm());
                                stckW1Hist.setInoutCd("OUT");
                                stckW1Hist.setInoutQty(requestData.getColQty());
                                stckW1Hist.setChgDvsn("ROUT");
                                stckW1Hist.setRelationNo(rtnMgntUnqNo);  //======================================
                                stckMgntDtlHistList.add(stckW1Hist);

                                //반품 금액 계산
                                acctbalAmt = acctbalAmt +  (targetData.getPickDtlInfo().getUnitAmt() * requestData.getColQty()) ;

                            } else if (targetData.getColDvsn().equals("C002") && requestData.getColQty() > 0) {
                                //  공급사 수거일경우 - 본사창고 재고 차감 처리
                                // 1. 참감처리 , 2. 반품처리테이블 생성, 3. 수거서 업데이타, 4, 반품발주건 업데이트
                                // 본사재고 차감 처리  stck_mgnt_base_info  stck_mgnt_dtl_hist
                                StckMgntBaseInfoEntity stckWEntity = new StckMgntBaseInfoEntity();
                                stckWEntity.setBrandId(saveRtnStockProcRequest.getBrandId());
                                stckWEntity.setWhsId(saveRtnStockProcRequest.getRtnWhsId());
                                stckWEntity.setLocation(targetData.getRtnLocation());
                                stckWEntity.setItemId(requestData.getItemId());
                                stckWEntity.setStckQty(requestData.getColQty() * (-1));
                                stckWEntity.setUnit(targetData.getPickDtlInfo().getUnit());
                                stckMgntBaseInfoList.add(stckWEntity);

                                // 재고 이력정보 등록
                                StckMgntDtlHistEntity stckWHist = new StckMgntDtlHistEntity();
                                stckWHist.setStckMgntDtlNo(fnGetDealNo(37, ""));
                                stckWHist.setBrandId(saveRtnStockProcRequest.getBrandId());
                                stckWHist.setWhsId(saveRtnStockProcRequest.getRtnWhsId());
                                stckWHist.setLocation(targetData.getRtnLocation());
                                stckWHist.setItemId(requestData.getItemId());
                                stckWHist.setItemNm(targetData.getPickDtlInfo().getItemNm());
                                stckWHist.setInoutCd("OUT");
                                stckWHist.setInoutQty(requestData.getColQty());
                                stckWHist.setChgDvsn("ROUT");
                                stckWHist.setRelationNo(rtnMgntUnqNo);  //======================================
                                stckMgntDtlHistList.add(stckWHist);
                            }

                            if (targetData.getColDvsn().equals("C001")) {  // 본사수거지시 일 경우
                                ColOdrDtlPtclEntity colOdrDtlPtclEntity = new ColOdrDtlPtclEntity();
                                colOdrDtlPtclEntity.setColCmdUnqNo(targetData.getPickDtlInfo().getColCmdUnqNo());
                                colOdrDtlPtclEntity.setColCmdDtlNo(targetData.getPickDtlInfo().getColCmdDtlNo());
                                if (requestData.getColQty() > 0) {
                                    colOdrDtlPtclEntity.setColCmdDtlStCd("CDLD2");
                                } else {
                                    colOdrDtlPtclEntity.setColCmdDtlStCd("COLD3");
                                }
                                colOdrDtlPtclList.add(colOdrDtlPtclEntity);

                                ColOdrBaseEntity colOdrBase = new ColOdrBaseEntity();
                                colOdrBase.setColCmdUnqNo(targetData.getPickDtlInfo().getColCmdUnqNo());
                                colOdrBaseList.add(colOdrBase);
                            }

                            // 수거서 건별 업데이트
                            PickDtlPtclEntity pickDtlPtclEntity = new PickDtlPtclEntity();
                            pickDtlPtclEntity.setColPickUnqNo(targetData.getColPickUnqNo());
                            pickDtlPtclEntity.setColPickDtlNo(targetData.getPickDtlInfo().getColPickDtlNo());
                            pickDtlPtclEntity.setColQty(requestData.getColQty());
                            pickDtlPtclEntity.setColAmt(requestData.getColQty() * targetData.getPickDtlInfo().getUnitAmt());
                            if (requestData.getColQty() > 0) {
                                pickDtlPtclEntity.setPickDtlStCd("PICKD1");
                            } else {
                                pickDtlPtclEntity.setPickDtlStCd("PICKD3");
                            }
                            pickDtlPtclList.add(pickDtlPtclEntity);

                            PickInfoMgntEntity pickInfoEntity = new PickInfoMgntEntity();
                            pickInfoEntity.setColPickUnqNo(targetData.getColPickUnqNo());
                            pickInfoMgntList.add(pickInfoEntity);
                        }

                    } //==> targetList db에서 가온 수거정보
                } //==> request에서 가져온 전달받은 정보

                //정보 저장함
                if (rtnProcInfoPtclList.size() > 0 ) {
                    colOdrMapper.insertRtnProcInfoPtcl(userId,rtnProcInfoPtclList );
                }

                if (stckMgntBaseInfoList.size() > 0 ) {
                    stockMngMapper.insertInOutStckMgntBaseInfo(userId, stckMgntBaseInfoList);
                }

                if (stckMgntDtlHistList.size() > 0 ) {
                    stockMngMapper.insertMultiStckMgntDtlHist(userId, stckMgntDtlHistList);
                }

                if (colOdrDtlPtclList.size() > 0 ) {
                    colOdrMapper.updateChgStckCloDtlStCd(userId, colOdrDtlPtclList);
                }

                if (pickDtlPtclList.size() > 0 ) {
                    colOdrMapper.updateChgStckPickDtlStCd(userId, pickDtlPtclList);
                }

                // 마스터성 수거지시 마스터  업데이트
                if (colOdrBaseList.size() > 0 ) {
                    List<ColOdrBaseEntity>  colOdrStList = colOdrMapper.selectColCmdStDtlList(userId, colOdrBaseList);
                    colOdrMapper.updateChgStckColOdrStCd(userId,colOdrStList );
                }

                // 수거서 마스터 업데이트
                if (pickInfoMgntList.size() > 0 ) {
                    List<PickInfoMgntEntity>  pickInfoList = colOdrMapper.selectColPickStList(userId, pickInfoMgntList);
                    colOdrMapper.updateChgStckPickStCd(userId, pickInfoList);
                }

                //수거 반품 금액 매장에 정산처리함 acctbalAmt
                if (loanInfo != null && !"".toString().equals(saveRtnStockProcRequest.getStoreId())) {

                    if ("LD01".equals(loanInfo.getLoanDvsn()) || "LD02".equals(loanInfo.getLoanDvsn())) {
                        LoanMgntBaseInfoEntity loanEntity = new LoanMgntBaseInfoEntity();
                        loanEntity.setLoanMgntUnqNo(loanInfo.getLoanMgntUnqNo());
                        loanEntity.setStoreId(saveRtnStockProcRequest.getStoreId());
                        loanEntity.setAcctBal(acctbalAmt);
                        loanStateMapper.updateloanRtnacctBalAmt(userId, loanEntity);

                        LoanMgntDtlHstEntity hstEntity = new LoanMgntDtlHstEntity();
                        hstEntity.setLoanMgntUnqNo(loanInfo.getLoanMgntUnqNo());
                        hstEntity.setLoanRegDt(DateUtil.getCurrentDate());
                        hstEntity.setLoanRegTm(DateUtil.getCurrentTime());
                        hstEntity.setDpstPayDvsn(DpstPayDvsn.DEPOSIT.getCd());
                        hstEntity.setMediaDvsn(MediaDvsn.RTNC.getCd());
                        hstEntity.setPayType(PayType.RTN_PAYMENT.getCd());

                        hstEntity.setTrscAmt(acctbalAmt); // 거래금액
                        hstEntity.setTrscBfBal(loanInfo.getAcctBal());
                        hstEntity.setTrscAfBal(loanInfo.getAcctBal() + acctbalAmt);
                        dsptMngMapper.insertLoanMgntDtlHst(userId, hstEntity);
                    }
                }
            }

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

    /*
      반품처리현황 그리드 리스트 조회
 */
    public GridResponse selectRtnStockResultList(String sBrandId, String sStoreId, String sColPickUnqNo, String fromDt, String toDt, String sRtnWhsId, String sSpplyId, String sWhsId, String sItemNm, String sRtnPodrUnqNo, 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 = colOdrMapper.selectColRtnInstResultGridCnt(sBrandId, sStoreId,sColPickUnqNo, sRtnPodrUnqNo,  fromDt, toDt, sSpplyId, sRtnWhsId,  sWhsId,  sItemNm);
        int gridTotal = fnCalculateGridTotal(gridSize, gridRecords);
        List<PickInfoMgntEntity> entities = colOdrMapper.selectColRtnInstResultGridList(sBrandId, sStoreId, sColPickUnqNo, sRtnPodrUnqNo, fromDt, toDt, sSpplyId, sRtnWhsId, sWhsId, sItemNm, gridRequest);
        List<Object> gridRows = entities.stream()
                .map(m -> RtnColStockResultResponse.builder()
                        .viewCd("R")
                        .brandId(m.getBrandId() == null ? "" : m.getBrandId())
                        .brandNm(m.getBrandNm() == null ? "" : m.getBrandNm())
                        .colPickUnqNo(m.getColPickUnqNo() == null ? "" : m.getColPickUnqNo())
                        .colPickDtlNo(m.getPickDtlInfo() == null ? "" : m.getPickDtlInfo().getColPickDtlNo() == null ? "" :m.getPickDtlInfo().getColPickDtlNo() )
                        .rtnPodrUnqNo(m.getPickDtlInfo() == null ? "" : m.getPickDtlInfo().getRtnPodrUnqNo() == null ? "" :m.getPickDtlInfo().getRtnPodrUnqNo() )
                        .rtnPodrDtlNo(m.getPickDtlInfo() == null ? "" : m.getPickDtlInfo().getRtnPodrDtlNo() == null ? "" :m.getPickDtlInfo().getRtnPodrDtlNo() )
                        .itemId(m.getPickDtlInfo() == null ? "" : m.getPickDtlInfo().getItemId() == null ? "" :m.getPickDtlInfo().getItemId() )
                        .itemNm(m.getPickDtlInfo() == null ? "" : m.getPickDtlInfo().getItemNm() == null ? "" :m.getPickDtlInfo().getItemNm() )
                        .colQty(m.getPickDtlInfo() == null ? 0 : m.getPickDtlInfo().getColQty() == null ? 0 :m.getPickDtlInfo().getColQty() )
                        .colReqQty(m.getPickDtlInfo() == null ? 0 : m.getPickDtlInfo().getColReqQty() == null ? 0 :m.getPickDtlInfo().getColReqQty() )
                        .rodrQty(m.getPickDtlInfo() == null ? 0 : m.getPickDtlInfo().getRodrQty() == null ? 0 :m.getPickDtlInfo().getRodrQty() )
                        .colAmt(m.getPickDtlInfo() == null ? 0 : m.getPickDtlInfo().getColAmt() == null ? 0 :m.getPickDtlInfo().getColAmt() )
                        .whsId(m.getWhsId() == null ? "" : m.getWhsId())
                        .location(m.getLocation() == null ? "" : m.getLocation())
                        .whsNm(m.getWhsNm() == null ? "" : m.getWhsNm() + " - " + m.getLocationNm())
                        .rtnWhsId(m.getRtnWhsId() == null ? "" : m.getRtnWhsId())
                        .rtnLocation(m.getRtnLocation() == null ? "" : m.getRtnLocation())
                        .rtnWhsNm(m.getRtnWhsNm() == null ? "" : m.getRtnWhsNm())
                        .colSchDt(m.getColSchDt() == null ? "" : m.getColSchDt())
                        .colCmpltDt(m.getColCmpltDt() == null ? "" : m.getColCmpltDt())
                        .pickDtlStCd(m.getPickDtlInfo() == null ? "" : m.getPickDtlInfo().getPickDtlStCd() == null ? "" : m.getPickDtlInfo().getPickDtlStCd())
                        .pickDtlStNm(m.getPickDtlInfo() == null ? "" : m.getPickDtlInfo().getPickDtlStNm() == null ? "" : m.getPickDtlInfo().getPickDtlStNm())
                        .pickMgrNm(m.getPickMgrNm() == null ? "" : m.getPickMgrNm())
                        .pickMgrTelNo(m.getPickMgrTelNo() == null ? "" : m.getPickMgrTelNo())
                        .spplyId(m.getSpplyId() == null ? "" : m.getSpplyId())
                        .spplyNm(m.getSpplyNm() == null ? "" : m.getSpplyNm())
                        .build())
                .collect(Collectors.toList());
        return GridResponse.toDTO(gridPage, gridTotal, gridRecords, gridRows);
    }


}



