package com.oqpo.api.service.pomng;


import com.oqpo.api.entity.loanmng.LoanMgntBaseInfoEntity;
import com.oqpo.api.entity.oper.UserMngEntity;
import com.oqpo.api.entity.pomng.PchReqBaseInfoEntity;
import com.oqpo.api.entity.pomng.PchReqDtlPtclEntity;
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.service.CommonService;
import com.oqpo.api.util.DateUtil;
import com.oqpo.api.web.dto.request.GridRequest;
import com.oqpo.api.web.dto.request.pomng.pchReq.SavePchReqlRequest;
import com.oqpo.api.web.dto.response.GridResponse;
import com.oqpo.api.web.dto.response.pomng.pchReq.*;
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.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class PchReqService extends CommonService {
    @Autowired
    private PchReqMapper pchReqMapper;

    @Autowired
    private UserMngMapper userMngMapper;

    @Autowired
    private LoanStateMapper loanStateMapper;

    /* 구매요청  초기 정보 */
    public PchReqInitInfoResponse selectPchReqInitInfo(String userId) throws Exception {

        UserMngEntity uEntity = userMngMapper.selectGroupUserInfo(userId);

        LoanMgntBaseInfoEntity loanEntity = new LoanMgntBaseInfoEntity();
        if ("50".equals(uEntity.getAuthTpCd())) {
            loanEntity = loanStateMapper.selectLoanJobDataInfo(userId);
        }
        return PchReqInitInfoResponse.toDTO(uEntity,loanEntity);
    }

    /*
      구매요청 그리드 리스트 조회
     */
    public GridResponse selectPchReqGridList(String userId, String sBrandId, String sStoreId, String fromDt, String toDt, String sWhsId, String sPchReqStCd, 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()) && "".equals(sStoreId)) {
            throw new GlobalException(SystemMessageCode.ERR_NONSTOREID);
        }

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

        int gridRecords = pchReqMapper.selectPchReqGridCnt( sBrandId,sStoreId,  fromDt, toDt, sWhsId,sPchReqStCd, sItemNm );
        int gridTotal = fnCalculateGridTotal(gridSize, gridRecords);
        List<PchReqBaseInfoEntity> entities = pchReqMapper.selectPchReqGridList( sBrandId, sStoreId, fromDt, toDt, sWhsId,sPchReqStCd, sItemNm, gridRequest);
        List<Object> gridRows = entities.stream()
                .map(m -> PchReqSearchListResponse.builder()
                        .viewCd("R")
                        .pchReqUnqNo(m.getPchReqUnqNo())
                        .brandId(m.getBrandId())
                        .brandNm(m.getBrandNm())
                        .storeId(m.getStoreId()  == null ? "" : m.getStoreId())
                        .pchReqNm(m.getPchReqNm() == null ? "" :m.getPchReqNm() )
                        .pchReqStCd(m.getPchReqStCd() == null ? "" : m.getPchReqStCd())
                        .pchReqStNm(m.getPchReqStNm() == null ? "" : m.getPchReqStNm())
                        .pchReqItemQty(m.getPchReqItemQty() == null ? 0 : m.getPchReqItemQty())
                        .pchReqTotalAmt(m.getPchReqTotalAmt() == null ? 0 : m.getPchReqTotalAmt())
                        .pchReqRjctDt(m.getPchReqRjctDt() == null ? "" :m.getPchReqRjctDt() )
                        .pchReqRjctNm(m.getPchReqRjctNm() == null ? "" : m.getPchReqRjctNm())
                        .pchReqMgrNm(m.getPchReqMgrNm() == null ? "" :m.getPchReqMgrNm() )
                        .dlvReqDt(m.getDlvReqDt() == null ? "" :m.getDlvReqDt() )
                        .whsLocationNm(m.getWhsNm() == null ? "" : m.getWhsNm()  + "-" + m.getLocationNm())
                        .build())
                .collect(Collectors.toList());
        return GridResponse.toDTO(gridPage, gridTotal, gridRecords, gridRows);
    }

    /* 구매요청 정보 */
    public PchReqInfoResponse selectPchReqInfo(String brandId, String  pchReqUnqNo) throws Exception {

        PchReqBaseInfoEntity entity = pchReqMapper.selectPchReqInfo(brandId, pchReqUnqNo);
        List<PchReqDtlPtclEntity> dtlEntity = pchReqMapper.selectPchReqDtlPtcl(brandId, pchReqUnqNo);

        //구매요청 기본정보
        UserMngEntity uEntity = userMngMapper.selectGroupUserInfo(entity.getPchReqMgrId());

        LoanMgntBaseInfoEntity loanEntity = new LoanMgntBaseInfoEntity();
        if ("50".equals(uEntity.getAuthTpCd())) {
            loanEntity = loanStateMapper.selectLoanJobDataInfo(entity.getPchReqMgrId());
        }
        return PchReqInfoResponse.toDTO(entity,uEntity,loanEntity, dtlEntity );
    }

    /* 구매요청 저장 */
    @Transactional
    public void savePchReqInfo(String userId, SavePchReqlRequest savePchReqlRequest) throws Exception {
        try {

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

            PchReqBaseInfoEntity entity = new PchReqBaseInfoEntity();
            entity.setPchReqUnqNo(savePchReqlRequest.getPchReqUnqNo());
            entity.setBrandId(savePchReqlRequest.getBrandId());
            entity.setStoreId(savePchReqlRequest.getStoreId());
            entity.setPchReqNm(savePchReqlRequest.getPchReqNm());
            entity.setNote(savePchReqlRequest.getNote());
            entity.setDlvReqDt(savePchReqlRequest.getDlvReqDt().replaceAll("\\.",""));
            entity.setWhsId(savePchReqlRequest.getWhsId());
            entity.setPchReqStCd(savePchReqlRequest.getPchReqStCd());
            entity.setLocation(savePchReqlRequest.getLocation());
            entity.setPchReqDvsn(savePchReqlRequest.getPchReqDvsn());


            if ("C".equals(savePchReqlRequest.getViewCd())) {
                // 구매요청 아이디 부여
                entity.setPchReqUnqNo(fnGetDealNo(13,""));  // 구매요청번호 생성
            }
            // 품목 삭제 처리
            List<PchReqDtlPtclEntity> gridDeleteData = savePchReqlRequest.toCodeEntities(savePchReqlRequest.getGridDeleteData());
            if (gridDeleteData.size() > 0) {
                pchReqMapper.deletePchReqDtlPtcl(entity.getPchReqUnqNo(), gridDeleteData) ;
            }

            // 품목 수정 처리
            List<PchReqDtlPtclEntity> gridUpdateData = savePchReqlRequest.toCodeEntities(savePchReqlRequest.getGridUpdateData());
            if (gridUpdateData.size() > 0) {
                pchReqMapper.updatePchReqDtlPtcl(userId, entity.getPchReqUnqNo(), gridUpdateData) ;
            }

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

                int maxDtlNo = pchReqMapper.selectMaxPchReqDtlNo(entity.getPchReqUnqNo());

                for (int i = 0 ; i < gridInsertData.size() ; i++) {
                    maxDtlNo = maxDtlNo + 10 ;
                    gridInsertData.get(i).setPchReqUnqNo(entity.getPchReqUnqNo());
                    gridInsertData.get(i).setPchReqDtlNo( Integer.toString(maxDtlNo ));
                }

                pchReqMapper.insertPchReqDtlPtcl(userId, gridInsertData) ;
            }


            PchReqBaseInfoEntity sumData = pchReqMapper.selectSumReqAmt(entity.getPchReqUnqNo());

            // 구매요청(PR20)일경우 여신의 사용금액에 추가처리함  비교로직도 필요함
            if ("PD01".equals(entity.getPchReqDvsn())  &&  "PR20".equals(entity.getPchReqStCd())) {
                LoanMgntBaseInfoEntity loanMgnInfo = loanStateMapper.selectLoanJobDataInfo(entity.getStoreId());

                if (loanMgnInfo.getOrdUseAmt() < sumData.getPchReqTotalAmt()) {
                    throw new GlobalException(SystemMessageCode.ERR_PCHREQAMTOVER);
                }

                loanStateMapper.updateloanPchReqUseAmt(savePchReqlRequest.getLoanMgntUnqNo(), entity.getStoreId(), sumData.getPchReqTotalAmt());

                if ("LD01".equals(loanMgnInfo.getLoanDvsn())) {  // 선불일경우 선결재금액 입력
                    entity.setPchApprAmt(sumData.getPchReqTotalAmt());
                }
            }

            entity.setPchReqItemQty(sumData.getPchReqItemQty());
            entity.setPchReqTotalAmt(sumData.getPchReqTotalAmt());


            if ("C".equals(savePchReqlRequest.getViewCd())) {
                if ("".equals(entity.getPchReqNm())) {
                    entity.setPchReqNm(userNm + " " + DateUtil.getCurrentDate() + DateUtil.getCurrentTime() + " " + gridInsertData.size());
                }
                entity.setPchReqMgrId(userId);
                entity.setPchReqMgrNm(userNm);

                pchReqMapper.insertPchReqBaseInfo(userId, userNm, entity);
            } else if ("U".equals(savePchReqlRequest.getViewCd())) {

                pchReqMapper.updateOrdPchReqBaseInfo(userId, userNm,  entity);
            }
        } catch (GlobalException e) {
            e.getStackTrace();
            throw new GlobalException(e.getSystemMessageCode());
        } catch (Exception e) {
            e.getStackTrace();
            throw new RuntimeException();
        }
    }

    /*
      구매요청 그리드 리스트 조회
     */
    public GridResponse selectPchReqPoTargetGridList(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 = pchReqMapper.selectPchReqPoTargetGridCnt( sBrandId,fromDt,  toDt, sSpplyId, sWhsId, sItemNm );
        int gridTotal = fnCalculateGridTotal(gridSize, gridRecords);
        List<PchReqBaseInfoEntity> entities = pchReqMapper.selectPchReqPoTargetGridList( sBrandId,fromDt,  toDt, sSpplyId, sWhsId, sItemNm, gridRequest);
        List<Object> gridRows = entities.stream()
                .map(m -> PchReqPoTargetSearchListResponse.builder()
                        .viewCd("R")
                        .pchReqUnqNo(m.getPchReqUnqNo())
                        .pchReqDtlNo(m.getPchReqDtlInfo() == null ? "" : m.getPchReqDtlInfo().getPchReqDtlNo() == null ? "" : m.getPchReqDtlInfo().getPchReqDtlNo() )
                        .brandId(m.getBrandId() == null ? "" : m.getBrandId())
                        .brandNm(m.getBrandNm() == null ? "" : m.getBrandNm())
                        .storeId(m.getStoreId() == null ? "" : m.getStoreId())
                        .storeNm(m.getStoreNm() == null ? "" : m.getStoreNm())
                        .spplyId(m.getItemUnitInfo() == null ? "" : m.getItemUnitInfo().getSpplyId() == null ? "" : m.getItemUnitInfo().getSpplyId())
                        .spplyNm(m.getItemUnitInfo() == null ? "" : m.getItemUnitInfo().getSpplyNm() == null ? "" : m.getItemUnitInfo().getSpplyNm())
                        .whsId(m.getWhsId() == null ? "" : m.getWhsId())
                        .whsNm(m.getWhsNm() == null ? "" : m.getWhsNm())
                        .location(m.getLocation() == null ? "" : m.getLocation())
                        .locationNm(m.getLocationNm() == null ? "" : m.getLocationNm())
                        .itemId(m.getPchReqDtlInfo() == null ? "" : m.getPchReqDtlInfo().getItemId() == null ? "" : m.getPchReqDtlInfo().getItemId())
                        .itemNm(m.getPchReqDtlInfo() == null ? "" : m.getPchReqDtlInfo().getItemNm() == null ? "" : m.getPchReqDtlInfo().getItemNm())
                        .unitAmt(m.getPchReqDtlInfo() == null ? 0 : m.getPchReqDtlInfo().getUnitAmt() == null ? 0 : m.getPchReqDtlInfo().getUnitAmt())
                        .poUnitAmt(m.getItemUnitInfo() == null ? 0 : m.getItemUnitInfo().getUnitAmt() == null ? 0 : m.getItemUnitInfo().getUnitAmt())
                        .pchReqQty(m.getPchReqDtlInfo() == null ? 0 : m.getPchReqDtlInfo().getPchReqQty() == null ? 0 : m.getPchReqDtlInfo().getPchReqQty())
                        .dlvReqDt(m.getDlvReqDt() == null ? "" : m.getDlvReqDt())
                        .pchReqAmt(m.getPchReqDtlInfo() == null ? 0 : m.getPchReqDtlInfo().getPchReqAmt() == null ? 0 : m.getPchReqDtlInfo().getPchReqAmt())
                        .pchOrdAmt(m.getPchReqDtlInfo() == null ? 0 : m.getPchReqDtlInfo().getPchOrdAmt() == null ? 0 : m.getPchReqDtlInfo().getPchOrdAmt())
                        .leadTime(m.getItemUnitInfo() == null ? 0 : m.getItemUnitInfo().getLeadTime() == null ? 0 : m.getItemUnitInfo().getLeadTime())
                        .build())
                .collect(Collectors.toList());
        return GridResponse.toDTO(gridPage, gridTotal, gridRecords, gridRows);
    }

    public PchReqRejectTargetResponse selectPchRejectPrTargetList(String pchReqUnqNo) throws Exception {
        return PchReqRejectTargetResponse.toDTO(pchReqMapper.selectPchRejectPrTargetList(pchReqUnqNo));
    }

    /* 구매요청 반려 처리 */
    @Transactional
    public void saveRejectPchReqInfo(String userId, String storeId, String pchReqUnqNo, String pchReqRjctRsn) throws Exception {
        try {
//
            // 로그인자 권한이 50 이면 매장 아이디 필수로 넘어와야함
            UserMngEntity uEntity = userMngMapper.selectGroupUserInfo(userId);
            String pchReqRjctNm = uEntity.getUserNm();
            pchReqMapper.updateRejPchReqBaseInfo(userId, pchReqUnqNo, pchReqRjctNm,pchReqRjctRsn);

            // 여신 사용금액 정리
            if (!"".equals(storeId)) {
                LoanMgntBaseInfoEntity loanMgnInfo = loanStateMapper.selectLoanJobDataInfo(storeId);
                PchReqBaseInfoEntity sumData = pchReqMapper.selectSumReqAmt(pchReqUnqNo);
                loanStateMapper.updateloanMinusPchReqUseAmt(loanMgnInfo.getLoanMgntUnqNo(), storeId, sumData.getPchReqTotalAmt());
            }


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