package com.oqpo.api.service.rtnmng;


import com.oqpo.api.entity.loanmng.LoanMgntBaseInfoEntity;
import com.oqpo.api.entity.oper.UserMngEntity;
import com.oqpo.api.entity.pomng.PchOdrDtlPtclEntity;
import com.oqpo.api.entity.pomng.PchReqBaseInfoEntity;
import com.oqpo.api.entity.pomng.PchReqDtlPtclEntity;
import com.oqpo.api.entity.rtnmng.RtnReqBaseInfoEntity;
import com.oqpo.api.entity.rtnmng.RtnReqDtlPtclEntity;
import com.oqpo.api.entity.stinfo.BrandEntity;
import com.oqpo.api.entity.stockmng.WhsMgntBaseInfoEntity;
import com.oqpo.api.enums.SystemMessageCode;
import com.oqpo.api.exception.GlobalException;
import com.oqpo.api.mapper.loanmng.LoanStateMapper;
import com.oqpo.api.mapper.oper.UserMngMapper;
import com.oqpo.api.mapper.pomng.PchReqMapper;
import com.oqpo.api.mapper.rtnmng.RtnReqMapper;
import com.oqpo.api.mapper.stinfo.BrandMapper;
import com.oqpo.api.mapper.stockmng.WhsMngMapper;
import com.oqpo.api.service.CommonService;
import com.oqpo.api.service.PushService;
import com.oqpo.api.util.DateUtil;
import com.oqpo.api.util.StringUtil;
import com.oqpo.api.web.dto.request.GridRequest;
import com.oqpo.api.web.dto.request.pomng.pchReq.PchReqInitInfoRequest;
import com.oqpo.api.web.dto.request.pomng.pchReq.SavePchReqlRequest;
import com.oqpo.api.web.dto.request.rtnmng.SaveRtnReqlRequest;
import com.oqpo.api.web.dto.response.GridResponse;
import com.oqpo.api.web.dto.response.pomng.pchReq.*;
import com.oqpo.api.web.dto.response.rtnmng.rtnReq.*;
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 RtnReqService extends CommonService {
    @Autowired
    private RtnReqMapper rtnReqMapper;

    @Autowired
    private UserMngMapper userMngMapper;

    @Autowired
    private BrandMapper brandMapper;

    @Autowired
    private WhsMngMapper whsMngMapper;

    @Autowired
    private PushService pushService;

    /* 반품요청  초기 정보 */

    public RtnReqInitInfoResponse selectRtnReqInitInfo(String userId, PchReqInitInfoRequest pchReqInitInfoRequest) throws Exception {

        UserMngEntity uEntity = userMngMapper.selectGroupUserInfo(userId);
        BrandEntity brandEntity = new BrandEntity();
        List<WhsMgntBaseInfoEntity> whsMgntList = new ArrayList<WhsMgntBaseInfoEntity>();
        WhsMgntBaseInfoEntity whsEntity = new WhsMgntBaseInfoEntity();

        if ("30".equals(uEntity.getAuthTpCd())) {   // 브랜드그룹
            // 브랜드 정보 request 로 받아서 브랜드정보 가져와 넣어줌
            brandEntity = brandMapper.selectBrandNmInfo(pchReqInitInfoRequest.getBrandId());
            uEntity.setBrandId(pchReqInitInfoRequest.getBrandId());
            uEntity.setBrandNm(brandEntity.getBrandNm());

        } else if ("40".equals(uEntity.getAuthTpCd())) {  // 브랜드
            if (!pchReqInitInfoRequest.getBrandId().equals(uEntity.getBrandId())) {
                throw new GlobalException(SystemMessageCode.ERR_NOTBRANDBELONG);
            }
        } else if ("50".equals(uEntity.getAuthTpCd())) {  // 매장
            if (StringUtil.isEmpty(pchReqInitInfoRequest.getStoreId())) {
                throw new GlobalException(SystemMessageCode.ERR_NONSTOREID);
            }

            if (!pchReqInitInfoRequest.getBrandId().equals(uEntity.getBrandId())) {
                throw new GlobalException(SystemMessageCode.ERR_NOTBRANDBELONG);
            }

            if (!pchReqInitInfoRequest.getStoreId().equals(uEntity.getStoreId())) {
                throw new GlobalException(SystemMessageCode.ERR_NOTSTOREBELONG);
            }

            //납품창고 정보 가져오기  selectStoreWhsLocList
            whsMgntList = whsMngMapper.selectStoreWhsLocList(pchReqInitInfoRequest.getBrandId(), pchReqInitInfoRequest.getStoreId());

            if (whsMgntList.size() == 1) {
                whsEntity = whsMgntList.get(0);
            }

        } else {
            // 브랜드 정보 request 로 받아서 브랜드정보 가져와 넣어줌
            brandEntity = brandMapper.selectBrandNmInfo(pchReqInitInfoRequest.getBrandId());
            uEntity.setBrandId(pchReqInitInfoRequest.getBrandId());
            uEntity.setBrandNm(brandEntity.getBrandNm());
        }

        return RtnReqInitInfoResponse.toDTO(uEntity, whsEntity);

    }

    /* 반품요청 저장 */
    @Transactional
    public void saveRtnReqInfo(String userId, SaveRtnReqlRequest saveRtnReqlRequest) throws Exception {
        try {

            // 로그인자 권한이 50 이면 매장 아이디 필수로 넘어와야함
            UserMngEntity uEntity = userMngMapper.selectGroupUserInfo(userId);
            String userNm = uEntity.getUserNm();

            if ("50".equals(uEntity.getAuthTpCd())) {
                if (StringUtil.isEmpty(saveRtnReqlRequest.getStoreId())) {
                    throw new GlobalException(SystemMessageCode.ERR_NONSTOREID);
                }

                if (!saveRtnReqlRequest.getBrandId().equals(uEntity.getBrandId())) {
                    throw new GlobalException(SystemMessageCode.ERR_NOTBRANDBELONG);
                }

                if (!saveRtnReqlRequest.getStoreId().equals(uEntity.getStoreId())) {
                    throw new GlobalException(SystemMessageCode.ERR_NOTSTOREBELONG);
                }
            } else if ("40".equals(uEntity.getAuthTpCd())) {
                if (!saveRtnReqlRequest.getBrandId().equals(uEntity.getBrandId())) {
                    throw new GlobalException(SystemMessageCode.ERR_NOTBRANDBELONG);
                }
            }


            RtnReqBaseInfoEntity entity = new RtnReqBaseInfoEntity();

            String rtnReqUnqNo = "";
            if ("C".toString().equals(saveRtnReqlRequest.getViewCd())) {
                // 신규번호 생성
                entity.setRtnReqUnqNo(fnGetDealNo(18, ""));
            } else {
                entity.setRtnReqUnqNo(saveRtnReqlRequest.getRtnReqUnqNo());
            }

            entity.setBrandId(saveRtnReqlRequest.getBrandId());
            entity.setStoreId(saveRtnReqlRequest.getStoreId());
            entity.setRtnReqStCd(saveRtnReqlRequest.getRtnReqStCd());
            entity.setNote(saveRtnReqlRequest.getNote());
            entity.setColReqDt(saveRtnReqlRequest.getColReqDt().replaceAll("\\.", ""));
            entity.setRtnWhsId(saveRtnReqlRequest.getRtnWhsId());
            entity.setRtnLocation(saveRtnReqlRequest.getRtnLocation());
            entity.setRtnReqMgrNm(userNm);
            entity.setRtnReqMgrTelNo(uEntity.getTelNo());
            entity.setWhsDvsn(saveRtnReqlRequest.getWhsDvsn());


            // 품목 삭제 처리
            List<RtnReqDtlPtclEntity> gridDeleteData = saveRtnReqlRequest.toCodeEntities(saveRtnReqlRequest.getGridDeleteData());
            if (gridDeleteData.size() > 0) {
                rtnReqMapper.deleteRtnReqDtlPtcl(entity.getRtnReqUnqNo(), gridDeleteData);
            }

            // 품목 수정 처리
            List<RtnReqDtlPtclEntity> gridUpdateData = saveRtnReqlRequest.toCodeEntities(saveRtnReqlRequest.getGridUpdateData());
            if (gridUpdateData.size() > 0) {
                rtnReqMapper.updateRtnReqDtlPtcl(userId, gridUpdateData);
            }

            // 품목 등록 처리
            List<RtnReqDtlPtclEntity> gridInsertData = saveRtnReqlRequest.toCodeEntities(saveRtnReqlRequest.getGridInsertData());
            if (gridInsertData.size() > 0) {

                int maxDtlNo = rtnReqMapper.selectMaxRtnReqDtlNo(entity.getRtnReqUnqNo());

                for (int i = 0; i < gridInsertData.size(); i++) {
                    maxDtlNo = maxDtlNo + 10;
                    gridInsertData.get(i).setRtnReqUnqNo(entity.getRtnReqUnqNo());
                    gridInsertData.get(i).setRtnReqDtlNo(Integer.toString(maxDtlNo));
                    if (gridInsertData.get(i).getStoreUnitUnqNo() == null || StringUtil.isEmpty(gridInsertData.get(i).getStoreUnitUnqNo())) {
                        gridInsertData.get(i).setUnitGubun("B");
                    } else {
                        gridInsertData.get(i).setUnitGubun("S");
                    }

                }

                rtnReqMapper.insertRtnReqDtlPtcl(userId, gridInsertData);
            }

            RtnReqBaseInfoEntity sumData = rtnReqMapper.selectSumRtnAmt(entity.getRtnReqUnqNo());
            entity.setRtnReqAmt(sumData.getRtnReqAmt());
            entity.setRtnReqItemQty(sumData.getRtnReqItemQty());

            if ("C".toString().equals(saveRtnReqlRequest.getViewCd())) {
                rtnReqMapper.insertRtnReqBaseInfo(userId, entity);
            } else {
                rtnReqMapper.updateRtnReqBaseInfo(userId, entity);
            }
            // 상세코드 업데이트
            if ("RR20".equals(saveRtnReqlRequest.getRtnReqStCd())) {
                rtnReqMapper.updateAllRtnReqDtlStCd(userId, entity.getRtnReqUnqNo(), "RRD20");
            } else {
                rtnReqMapper.updateAllRtnReqDtlStCd(userId, entity.getRtnReqUnqNo(), "RRD00");
            }

            // push서비스 호출
            log.info("====================================>" + saveRtnReqlRequest.getRtnReqStCd());
            if ("RR20".equals(saveRtnReqlRequest.getRtnReqStCd())) {
                log.info("=======================================pushSend");
                pushService.pushSend(saveRtnReqlRequest.getBrandId(),"RTN", entity.getRtnReqUnqNo());
            }

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

    /* 반품요청 그리드 리스트 */
    public GridResponse selectRtnReqGridList(String userId, String sBrandId, String sStoreId, String fromDt, String toDt, String sWhsId, String sRtnReqStCd, String sItemNm, GridRequest gridRequest) throws Exception {
        int gridPage = gridRequest.getGridPage();
        int gridSize = gridRequest.getGridSize();

        // 로그인자 권한이 50 이면 매장 아이디 필수로 넘어와야함
        UserMngEntity uEntity = userMngMapper.selectGroupUserInfo(userId);

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

            if (!sBrandId.equals(uEntity.getBrandId())) {
                throw new GlobalException(SystemMessageCode.ERR_NOTBRANDBELONG);
            }

            if (!sStoreId.equals(uEntity.getStoreId())) {
                throw new GlobalException(SystemMessageCode.ERR_NOTSTOREBELONG);
            }
        } else if ("40".equals(uEntity.getAuthTpCd())) {
            if (!sBrandId.equals(uEntity.getBrandId())) {
                throw new GlobalException(SystemMessageCode.ERR_NOTBRANDBELONG);
            }
        }


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

        int gridRecords = rtnReqMapper.selectRtnReqGridCnt(sBrandId, sStoreId, fromDt, toDt, sWhsId, sRtnReqStCd, sItemNm);
        int gridTotal = fnCalculateGridTotal(gridSize, gridRecords);
        List<RtnReqBaseInfoEntity> entities = rtnReqMapper.selectRtnReqGridList(sBrandId, sStoreId, fromDt, toDt, sWhsId, sRtnReqStCd, sItemNm, gridRequest);
        List<Object> gridRows = entities.stream()
                .map(m -> RtnReqSearchListResponse.builder()
                        .viewCd("R")
                        .rtnReqUnqNo(m.getRtnReqUnqNo() == null ? "" : m.getRtnReqUnqNo())
                        .brandId(m.getBrandId() == null ? "" : m.getBrandId())
                        .brandNm(m.getBrandNm() == null ? "" : m.getBrandNm())
                        .storeId(m.getStoreId() == null ? "" : m.getStoreId())
                        .storeNm(m.getStoreNm() == null ? "" : m.getStoreNm())
                        .rtnReqStCd(m.getRtnReqStCd() == null ? "" : m.getRtnReqStCd())
                        .rtnReqStNm(m.getRtnReqStNm() == null ? "" : m.getRtnReqStNm())
                        .rtnWhsNm(m.getRtnWhsNm() == null ? "" : m.getRtnWhsNm() + " - " + m.getRtnLocationNm())
                        .rtnReqDt(m.getRtnReqDt() == null ? "" : m.getRtnReqDt())
                        .rtnReqItemQty(m.getRtnReqItemQty() == null ? 0 : m.getRtnReqItemQty())
                        .rtnReqAmt(m.getRtnReqAmt() == null ? 0 : m.getRtnReqAmt())
                        .colReqDt(m.getColReqDt() == null ? "" : m.getColReqDt())
                        .rtnReqMgrId(m.getRtnReqMgrId() == null ? "" : m.getRtnReqMgrId())
                        .rtnReqMgrNm(m.getRtnReqMgrNm() == null ? "" : m.getRtnReqMgrNm())
                        .rtnRjctDt(m.getRtnRjctDt() == null ? "" : m.getRtnRjctDt())
                        .rtnRjctNm(m.getRtnRjctNm() == null ? "" : m.getRtnRjctNm())
                        .build())
                .collect(Collectors.toList());
        return GridResponse.toDTO(gridPage, gridTotal, gridRecords, gridRows);
    }


    /* 반품요청 정보 */
    public RtnReqInfoResponse selectRtnReqInfo(String userId, String brandId, String rtnReqUnqNo) throws Exception {

        String storeId = "";

        // 로그인자 권한이 50 이면 매장 아이디 필수로 넘어와야함
        UserMngEntity uEntity = userMngMapper.selectGroupUserInfo(userId);

        if ("50".equals(uEntity.getAuthTpCd())) {

            if (!brandId.equals(uEntity.getBrandId())) {
                throw new GlobalException(SystemMessageCode.ERR_NOTBRANDBELONG);
            }

            storeId = uEntity.getStoreId();

        } else if ("40".equals(uEntity.getAuthTpCd())) {
            if (!brandId.equals(uEntity.getBrandId())) {
                throw new GlobalException(SystemMessageCode.ERR_NOTBRANDBELONG);
            }
        }

        RtnReqBaseInfoEntity entity = rtnReqMapper.selectRtnReqInfo(brandId, storeId, rtnReqUnqNo);
        List<RtnReqDtlPtclEntity> dtlEntity = rtnReqMapper.selectRtnReqDtlList(rtnReqUnqNo);


        return RtnReqInfoResponse.toDTO(entity, dtlEntity);
    }


    /* 반품발주 대상 그리드 리스트 */
    public GridResponse selectRtnReqTargetGridList(String userId, String sBrandId, String sStoreId, String fromDt, String toDt, String sWhsId, String sSpplyId, String sItemNm, GridRequest gridRequest) throws Exception {
        int gridPage = gridRequest.getGridPage();
        int gridSize = gridRequest.getGridSize();

        // 로그인자 권한이 50 이면 매장 아이디 필수로 넘어와야함
        UserMngEntity uEntity = userMngMapper.selectGroupUserInfo(userId);

        if ("50".equals(uEntity.getAuthTpCd())) {
            throw new GlobalException(SystemMessageCode.ERR_NOTUSEDAUTH);
        } else if ("40".equals(uEntity.getAuthTpCd())) {
            if (!sBrandId.equals(uEntity.getBrandId())) {
                throw new GlobalException(SystemMessageCode.ERR_NOTBRANDBELONG);
            }
        }


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

        int gridRecords = rtnReqMapper.selectRtnReqTargetGridCnt(sBrandId, sStoreId, fromDt, toDt, sWhsId, sSpplyId, sItemNm);
        int gridTotal = fnCalculateGridTotal(gridSize, gridRecords);
        List<RtnReqBaseInfoEntity> entities = rtnReqMapper.selectRtnReqTargetGridList(sBrandId, sStoreId, fromDt, toDt, sWhsId, sSpplyId, sItemNm, gridRequest);
        List<Object> gridRows = entities.stream()
                .map(m -> RtnReqTargetSearchListResponse.builder()
                        .viewCd("R")
                        .rtnReqUnqNo(m.getRtnReqUnqNo() == null ? "" : m.getRtnReqUnqNo())
                        .rtnReqDtlNo(m.getRtnReqDtlInfo() == null ? "" : m.getRtnReqDtlInfo().getRtnReqDtlNo() == null ? "" : m.getRtnReqDtlInfo().getRtnReqDtlNo())
                        .brandId(m.getBrandId() == null ? "" : m.getBrandId())
                        .brandNm(m.getBrandNm() == null ? "" : m.getBrandNm())
                        .rtnWhsId(m.getRtnWhsId() == null ? "" : m.getRtnWhsId())
                        .rtnLocation(m.getRtnLocation() == null ? "" : m.getRtnLocation())
                        .rtnWhsNm(m.getRtnWhsNm() == null ? "" : m.getRtnWhsNm())
                        .rtnLocationNm(m.getRtnLocationNm() == null ? "" : m.getRtnLocationNm())
                        .spplyId(m.getRtnReqDtlInfo() == null ? "" : m.getRtnReqDtlInfo().getSpplyId() == null ? "" : m.getRtnReqDtlInfo().getSpplyId())
                        .spplyNm(m.getRtnReqDtlInfo() == null ? "" : m.getRtnReqDtlInfo().getSpplyNm() == null ? "" : m.getRtnReqDtlInfo().getSpplyNm())
                        .itemId(m.getRtnReqDtlInfo() == null ? "" : m.getRtnReqDtlInfo().getItemId() == null ? "" : m.getRtnReqDtlInfo().getItemId())
                        .itemNm(m.getRtnReqDtlInfo() == null ? "" : m.getRtnReqDtlInfo().getItemNm() == null ? "" : m.getRtnReqDtlInfo().getItemNm())
                        .rtnQty(m.getRtnReqDtlInfo() == null ? 0 : m.getRtnReqDtlInfo().getRtnQty() == null ? 0 : m.getRtnReqDtlInfo().getRtnQty())
                        .rtnAmt(m.getRtnReqDtlInfo() == null ? 0 : m.getRtnReqDtlInfo().getRtnAmt() == null ? 0 : m.getRtnReqDtlInfo().getRtnAmt())
                        .rtnDvsn(m.getRtnReqDtlInfo() == null ? "" : m.getRtnReqDtlInfo().getRtnDvsn() == null ? "" : m.getRtnReqDtlInfo().getRtnDvsn())
                        .rtnDvsnNm(m.getRtnReqDtlInfo() == null ? "" : m.getRtnReqDtlInfo().getRtnDvsnNm() == null ? "" : m.getRtnReqDtlInfo().getRtnDvsnNm())

                        .colDvsn(m.getRtnReqDtlInfo() == null ? "" : m.getRtnReqDtlInfo().getColDvsn() == null ? "" : m.getRtnReqDtlInfo().getColDvsn())
                        .colDvsnNm(m.getRtnReqDtlInfo() == null ? "" : m.getRtnReqDtlInfo().getColDvsnNm() == null ? "" : m.getRtnReqDtlInfo().getColDvsnNm())

                        .rtnReqDt(m.getRtnReqDt() == null ? "" : m.getRtnReqDt())
                        .colReqDt(m.getColReqDt() == null ? "" : m.getColReqDt())
                        .rtnRsnDvsn(m.getRtnReqDtlInfo() == null ? "" : m.getRtnReqDtlInfo().getRtnRsnDvsn() == null ? "" : m.getRtnReqDtlInfo().getRtnRsnDvsn())
                        .rtnRsnDvsnNm(m.getRtnReqDtlInfo() == null ? "" : m.getRtnReqDtlInfo().getRtnRsnDvsnNm() == null ? "" : m.getRtnReqDtlInfo().getRtnRsnDvsnNm() //
                                + (m.getRtnReqDtlInfo().getRtnRsn() == null ? "" : "(" + m.getRtnReqDtlInfo().getRtnRsn() + ")"))
                        .storeId(m.getStoreId() == null ? "" : m.getStoreId())
                        .whsDvsn(m.getWhsDvsn() == null ? "" : m.getWhsDvsn())
                        .whsDvsnNm(m.getWhsDvsnNm() == null ? "" : m.getWhsDvsnNm())
                        .build())
                .collect(Collectors.toList());
        return GridResponse.toDTO(gridPage, gridTotal, gridRecords, gridRows);
    }

    /* 반품요청 대상 리스트 */
    public RtnReqRejectTargetResponse selectRtnRejectPrTargetList(String pchReqUnqNo) throws Exception {
        return RtnReqRejectTargetResponse.toDTO(rtnReqMapper.selectRtnRejectPrTargetList(pchReqUnqNo));
    }


    /* 반품요청 반려 처리 */
    @Transactional
    public void saveRejRtnReqBaseInfo(String userId, String rtnReqUnqNo, String rtnRjctRsn) throws Exception {
        try {
            UserMngEntity uEntity = userMngMapper.selectGroupUserInfo(userId);
            String pchReqRjctNm = uEntity.getUserNm();

            // 이미 진행중인 품목이 있으면 반려 진행을 할 수 없습니다.
            int cnt = rtnReqMapper.selectRtnRejectIngCnt(rtnReqUnqNo);
            if (cnt > 0) {
                throw new GlobalException(SystemMessageCode.ERR_INGPOCNT);
            }
            // 상세코드 반려처리 RRD40
            String rtnReqDtlStCd = "RRD40";
            rtnReqMapper.updateRejRtnReqBaseInfo(userId, rtnReqUnqNo, rtnRjctRsn, uEntity.getUserNm());
            rtnReqMapper.updateAllRtnReqDtlStCd(userId, rtnReqUnqNo, rtnReqDtlStCd);


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


    public String selectRtnReqDtlStatusList(String rtnReqUnqNo) throws Exception {
        //PCH_ODR_ST_CD
        String rtnReqStCd = "";
        List<RtnReqDtlPtclEntity> dtlEntity = rtnReqMapper.selectRtnReqDtlStatusList(rtnReqUnqNo);

        int rrd00 = 0;
        int rrd20 = 0;
        int rrd30 = 0;
        int rrd40 = 0;
        int rrd99 = 0;

        for (int i = 0; i < dtlEntity.size(); i++) {
            RtnReqDtlPtclEntity entity = dtlEntity.get(i);
            if ("RRD00".equals(entity.getRtnReqDtlStCd())) {  // 임시저장
                rrd00 = rrd00 + entity.getRtnReqStatusCnt();
            } else if ("RRD20".equals(entity.getRtnReqDtlStCd())) {  // 요청
                rrd20 = rrd20 + entity.getRtnReqStatusCnt();
            } else if ("RRD30".equals(entity.getRtnReqDtlStCd())) {  //접수
                rrd30 = rrd30 + entity.getRtnReqStatusCnt();
            } else if ("RRD40".equals(entity.getRtnReqDtlStCd())) {  //반려
                rrd40 = rrd40 + entity.getRtnReqStatusCnt();
            } else if ("RRD99".equals(entity.getRtnReqDtlStCd())) {  //반려
                rrd99 = rrd40 + entity.getRtnReqStatusCnt();
            }
        }

        if (rrd00 > 0) {
            rtnReqStCd = "RR00";  //임시저장
        } else if (rrd00 == 0 && rrd20 > 0) {
            rtnReqStCd = "RR20"; // 요청
        } else if (rrd00 == 0 && rrd20 == 0 && rrd30 > 0) {
            rtnReqStCd = "RR30"; // 접수
        } else if (rrd00 == 0 && rrd20 == 0 && rrd30 == 0 && rrd40 > 0) {
            rtnReqStCd = "RR40"; // 반려
        } else {
            rtnReqStCd = "RR99"; // 반려
        }


        return rtnReqStCd;
    }


    /* 간소화 반품발주 대상 그리드 리스트 */
    public GridResponse selectRtnReqStreamlineGridList(String userId, String sBrandId, String fromDt, String toDt, String sWhsId, String sRtnReqUnqNo, 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 = rtnReqMapper.selectRtnReqStreamlineCnt(sBrandId, fromDt, toDt, sWhsId, sRtnReqUnqNo);
        int gridTotal = fnCalculateGridTotal(gridSize, gridRecords);
        List<RtnReqBaseInfoEntity> entities = rtnReqMapper.selectRtnReqStreamlineGridList(sBrandId, fromDt, toDt, sWhsId, sRtnReqUnqNo, gridRequest);
        List<Object> gridRows = entities.stream()
                .map(m -> RtnReqTargetSearchListResponse.builder()
                        .viewCd("R")
                        .rtnReqUnqNo(m.getRtnReqUnqNo() == null ? "" : m.getRtnReqUnqNo())
                        .rtnReqDtlNo(m.getRtnReqDtlInfo() == null ? "" : m.getRtnReqDtlInfo().getRtnReqDtlNo() == null ? "" : m.getRtnReqDtlInfo().getRtnReqDtlNo())
                        .brandId(m.getBrandId() == null ? "" : m.getBrandId())
                        .brandNm(m.getBrandNm() == null ? "" : m.getBrandNm())
                        .rtnWhsId(m.getRtnWhsId() == null ? "" : m.getRtnWhsId())
                        .rtnLocation(m.getRtnLocation() == null ? "" : m.getRtnLocation())
                        .rtnWhsNm(m.getRtnWhsNm() == null ? "" : m.getRtnWhsNm())
                        .rtnLocationNm(m.getRtnLocationNm() == null ? "" : m.getRtnLocationNm())
                        .spplyId(m.getRtnReqDtlInfo() == null ? "" : m.getRtnReqDtlInfo().getSpplyId() == null ? "" : m.getRtnReqDtlInfo().getSpplyId())
                        .spplyNm(m.getRtnReqDtlInfo() == null ? "" : m.getRtnReqDtlInfo().getSpplyNm() == null ? "" : m.getRtnReqDtlInfo().getSpplyNm())
                        .itemId(m.getRtnReqDtlInfo() == null ? "" : m.getRtnReqDtlInfo().getItemId() == null ? "" : m.getRtnReqDtlInfo().getItemId())
                        .itemNm(m.getRtnReqDtlInfo() == null ? "" : m.getRtnReqDtlInfo().getItemNm() == null ? "" : m.getRtnReqDtlInfo().getItemNm())
                        .rtnQty(m.getRtnReqDtlInfo() == null ? 0 : m.getRtnReqDtlInfo().getRtnQty() == null ? 0 : m.getRtnReqDtlInfo().getRtnQty())
                        .rtnAmt(m.getRtnReqDtlInfo() == null ? 0 : m.getRtnReqDtlInfo().getRtnAmt() == null ? 0 : m.getRtnReqDtlInfo().getRtnAmt())
                        .rtnDvsn(m.getRtnReqDtlInfo() == null ? "" : m.getRtnReqDtlInfo().getRtnDvsn() == null ? "" : m.getRtnReqDtlInfo().getRtnDvsn())
                        .rtnDvsnNm(m.getRtnReqDtlInfo() == null ? "" : m.getRtnReqDtlInfo().getRtnDvsnNm() == null ? "" : m.getRtnReqDtlInfo().getRtnDvsnNm())
                        .rtnReqDt(m.getRtnReqDt() == null ? "" : m.getRtnReqDt())
                        .colReqDt(m.getColReqDt() == null ? "" : m.getColReqDt())
                        .rtnRsnDvsn(m.getRtnReqDtlInfo() == null ? "" : m.getRtnReqDtlInfo().getRtnRsnDvsn() == null ? "" : m.getRtnReqDtlInfo().getRtnRsnDvsn())
                        .rtnRsnDvsnNm(m.getRtnReqDtlInfo() == null ? "" : m.getRtnReqDtlInfo().getRtnRsnDvsnNm() == null ? "" : m.getRtnReqDtlInfo().getRtnRsnDvsnNm() //
                                + (m.getRtnReqDtlInfo().getRtnRsn() == null ? "" : "(" + m.getRtnReqDtlInfo().getRtnRsn() + ")"))
                        .storeId(m.getStoreId() == null ? "" : m.getStoreId())
                        .whsDvsn(m.getWhsDvsn() == null ? "" : m.getWhsDvsn())
                        .whsDvsnNm(m.getWhsDvsnNm() == null ? "" : m.getWhsDvsnNm())
                        .colDvsn(m.getRtnReqDtlInfo() == null ? "" : m.getRtnReqDtlInfo().getColDvsn() == null ? "" : m.getRtnReqDtlInfo().getColDvsn())
                        .colDvsnNm(m.getRtnReqDtlInfo() == null ? "" : m.getRtnReqDtlInfo().getColDvsnNm() == null ? "" : m.getRtnReqDtlInfo().getColDvsnNm())
                        .build())
                .collect(Collectors.toList());
        return GridResponse.toDTO(gridPage, gridTotal, gridRecords, gridRows);
    }
}
