package com.oqpo.api.service.stinfo;


import com.oqpo.api.entity.loan.LoanInfoEntity;
import com.oqpo.api.entity.oper.UserMngEntity;
import com.oqpo.api.entity.stinfo.StoreBaseInfoEntity;
import com.oqpo.api.entity.stockmng.WhsMgntBaseInfoEntity;
import com.oqpo.api.entity.stockmng.WhsMgntBaseLocEntity;
import com.oqpo.api.exception.GlobalException;
import com.oqpo.api.mapper.loan.LoanMgntMapper;
import com.oqpo.api.mapper.oper.UserMngMapper;
import com.oqpo.api.mapper.stinfo.BrandMapper;
import com.oqpo.api.mapper.stinfo.StoreBaseInfoMapper;
import com.oqpo.api.service.CommonService;
import com.oqpo.api.service.stockmng.WhsMngService;
import com.oqpo.api.web.dto.request.GridRequest;
import com.oqpo.api.web.dto.request.stinfo.store.SaveStoreInfolRequest;
import com.oqpo.api.web.dto.request.stockmng.SaveWhsInfoRequest;
import com.oqpo.api.web.dto.response.GridResponse;
import com.oqpo.api.web.dto.response.stinfo.store.StoreInfoResponse;
import com.oqpo.api.web.dto.response.stinfo.store.StorePopSearchResponse;
import com.oqpo.api.web.dto.response.stinfo.store.StoreSearchListResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
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 StoreBaseInfoService extends CommonService {
    @Autowired
    private StoreBaseInfoMapper storeBaseInfoMapper;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private UserMngMapper userMngMapper;

    @Autowired
    private BrandMapper brandMapper;

    @Autowired
    private LoanMgntMapper loanMgntMapper;


    @Autowired
    private WhsMngService whsMngService ;




    /*
      팝업 매장 리스트 조회
     */
    public GridResponse selectPopBrandGridList(String brandId, String storeNm, GridRequest gridRequest) throws Exception {
        int gridPage = gridRequest.getGridPage();
        int gridSize = gridRequest.getGridSize();

        int gridRecords = storeBaseInfoMapper.selectPopStoreGridCnt( brandId, storeNm);
        int gridTotal = fnCalculateGridTotal(gridSize, gridRecords);
        List<StoreBaseInfoEntity> entities = storeBaseInfoMapper.selectPopStoreGridList(brandId, storeNm, gridRequest);
        List<Object> gridRows = entities.stream()
                .map(m -> StorePopSearchResponse.builder()
                        .viewCd("R")
                        .brandId(m.getBrandId())
                        .brandNm(m.getBrandNm())
                        .storeId(m.getStoreId())
                        .storeNm(m.getStoreNm())
                        .storeStCd(m.getStoreStCd())
                        .storeStNm(m.getStoreStNm())
                        .build())
                .collect(Collectors.toList());
        return GridResponse.toDTO(gridPage, gridTotal, gridRecords, gridRows);
    }


    /*
      매장 그리드 리스트 조회
     */
    public GridResponse selectStoreGridList( String sBrandId, String searchDateType, String fromDt, String toDt, String sStoreDvsn, String sStoreStCd, String sLoanDvsn, String sStoreNm,   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 = storeBaseInfoMapper.selectStoreGridCnt( sBrandId, searchDateType, fromDt, toDt, sStoreDvsn, sStoreStCd, sLoanDvsn, sStoreNm);
        int gridTotal = fnCalculateGridTotal(gridSize, gridRecords);
        List<StoreBaseInfoEntity> entities = storeBaseInfoMapper.selectStoreGridList( sBrandId, searchDateType, fromDt, toDt, sStoreDvsn, sStoreStCd, sLoanDvsn, sStoreNm, gridRequest);
        List<Object> gridRows = entities.stream()
                .map(m -> StoreSearchListResponse.builder()
                        .viewCd("R")
                        .brandId(m.getBrandId())
                        .brandNm(m.getBrandNm())
                        .storeId(m.getStoreId())
                        .storeNm(m.getStoreNm())
                        .bsnsRegNo(m.getBsnsRegNo())
                        .storeDvsn(m.getStoreDvsn())
                        .storeDvsnNm(m.getStoreDvsnNm())
                        .storeStCd(m.getStoreStCd())
                        .storeStNm(m.getStoreStNm())
                        .sysRegDttm(m.getSysRegDttm())
                        .build())
                .collect(Collectors.toList());
        return GridResponse.toDTO(gridPage, gridTotal, gridRecords, gridRows);
    }

    /* 매장 정보 */
    public StoreInfoResponse selectStoreInfo(String brandId, String storeId) throws Exception {
        return StoreInfoResponse.toDTO(storeBaseInfoMapper.selectStoreInfo(brandId,storeId));
    }

    /* 매장정보 저장 */
    @Transactional
    public void saveStoreInfo(String userId, SaveStoreInfolRequest saveStoreInfolRequest) throws Exception {
        try {

            StoreBaseInfoEntity entity = new StoreBaseInfoEntity();
            entity.setBrandId(saveStoreInfolRequest.getBrandId());
            entity.setStoreId(saveStoreInfolRequest.getStoreId());
            entity.setStoreNm(saveStoreInfolRequest.getStoreNm());
            entity.setStoreDvsn(saveStoreInfolRequest.getStoreDvsn());
            entity.setMblNo(saveStoreInfolRequest.getMblNo().replaceAll("-",""));

            entity.setOpenDt(saveStoreInfolRequest.getOpenDt().replaceAll("\\.",""));

            entity.setCloseDt(saveStoreInfolRequest.getCloseDt() == null ? "" : saveStoreInfolRequest.getCloseDt().replaceAll("\\.",""));
            entity.setLoanMgntUnqNo(saveStoreInfolRequest.getLoanMgntUnqNo());
            entity.setLoanDvsn(saveStoreInfolRequest.getLoanDvsn());
            entity.setLimitAmt(saveStoreInfolRequest.getLimitAmt());
            entity.setZipNo(saveStoreInfolRequest.getZipNo());
            entity.setAddr1(saveStoreInfolRequest.getAddr1());
            entity.setAddr2(saveStoreInfolRequest.getAddr2());
            entity.setLatX(saveStoreInfolRequest.getLatX());
            entity.setLongY(saveStoreInfolRequest.getLongY());
            entity.setWhsUseYn(saveStoreInfolRequest.getWhsUseYn());
            entity.setTelNo(saveStoreInfolRequest.getTelNo().replaceAll("-",""));
            entity.setFaxNo(saveStoreInfolRequest.getFaxNo().replaceAll("-",""));
            entity.setEmalAddr(saveStoreInfolRequest.getEmalAddr());
            entity.setStoreStCd(saveStoreInfolRequest.getStoreStCd());
            entity.setBsnsRegNo(saveStoreInfolRequest.getBsnsRegNo().replaceAll("-",""));
            entity.setCorpRegNo(saveStoreInfolRequest.getCorpRegNo().replaceAll("-",""));
            entity.setCtgrBsns(saveStoreInfolRequest.getCtgrBsns());
            entity.setBsnsCndt(saveStoreInfolRequest.getBsnsCndt());
            entity.setAreaCd(saveStoreInfolRequest.getAreaCd());
            entity.setBnkCd(saveStoreInfolRequest.getBnkCd());
            entity.setAcctNo(saveStoreInfolRequest.getAcctNo());
            entity.setOwacNm(saveStoreInfolRequest.getOwacNm());
            entity.setOwnerNm(saveStoreInfolRequest.getOwnerNm());

            if ("C".equals(saveStoreInfolRequest.getViewCd())) {

                // 매장 아이디 부여  22  entity.setContentsNo(fnGetKeyNo(17));
                LoanInfoEntity loanInfoEntity = new LoanInfoEntity();
                entity.setStoreId(fnGetKeyNo(24)); // 매장아이디 생성
                loanInfoEntity.setLoanMgntUnqNo(fnGetDealNo(29,""));  // 여신아이디 생성
                entity.setLoanMgntUnqNo(loanInfoEntity.getLoanMgntUnqNo());

                storeBaseInfoMapper.insertStoreInfo(userId, entity);

                //사용자 계정 정보 생성 및 권한생성
                UserMngEntity userEntity = new UserMngEntity();
                userEntity.setUserId(entity.getStoreId());
                userEntity.setUserNm(entity.getStoreNm());
                userEntity.setTelNo(entity.getTelNo());
                userEntity.setEmail(entity.getEmalAddr());

                if ("ST01".equals(entity.getStoreStCd())) {
                    userEntity.setUserStatCd("10");
                } else if ("ST03".equals(entity.getStoreStCd())) {
                    userEntity.setUserStatCd("90");
                } else {   //ST02
                    userEntity.setUserStatCd("30");
                }

                userEntity.setAuthTpCd("50");
                userEntity.setBrandId(entity.getBrandId());
                userEntity.setStoreId(entity.getStoreId());
                String afflShopId = brandMapper.selectBrandNo(entity.getBrandId());
                userEntity.setAfflShopId(afflShopId);

                //패스워드 암호화
                String password = passwordEncoder.encode(entity.getBsnsRegNo().replace("-",""));
                userEntity.setUserPw(password);
                userMngMapper.insertUserInfo(userId, userEntity);

                // 사용자 권한 등록
                userMngMapper.insertUserTypeAuth(entity.getStoreId(), userId, "50");

                //여신관련 정보 처리 진행
                /*
                  1. 여신 key 생성
                  2. 여신 데이타 생성 (insert)

                 */
                loanInfoEntity.setStoreId(entity.getStoreId());
                loanInfoEntity.setBrandId(entity.getBrandId());
                loanInfoEntity.setAcctBal(0);
                loanInfoEntity.setLoanDvsn(entity.getLoanDvsn());
                if ("LD01".equals(entity.getLoanDvsn())) {  //선불
                    loanInfoEntity.setChrgeLimitAmt(entity.getLimitAmt());
                    loanInfoEntity.setCredtLimitAmt(0);
                    loanInfoEntity.setCredtLimitUseYn("N");
                } else if ("LD02".equals(entity.getLoanDvsn())) {   // 후불
                        loanInfoEntity.setChrgeLimitAmt(0);
                        loanInfoEntity.setCredtLimitAmt(entity.getLimitAmt());
                        if (entity.getLimitAmt() > 0 ) {
                            loanInfoEntity.setCredtLimitUseYn("Y");
                        } else {
                            loanInfoEntity.setCredtLimitUseYn("N");
                        }
                } else if ("LD03".equals(entity.getLoanDvsn())) {   // 무정산
                    loanInfoEntity.setChrgeLimitAmt(0);
                    loanInfoEntity.setCredtLimitAmt(0);
                    loanInfoEntity.setCredtLimitUseYn("N");
                }
                loanInfoEntity.setUseAmtTotal(0);
                loanInfoEntity.setTmpRcvAcctTotal(0);
                loanInfoEntity.setUseYn("Y");
                loanInfoEntity.setLoanDesc("신규 매장생성");

                loanMgntMapper.insertLoanMgntInfo(userId, loanInfoEntity);


                // 창고정보저장
                WhsMgntBaseInfoEntity saveWhsInfo  = new WhsMgntBaseInfoEntity();

                saveWhsInfo.setBrandId(entity.getBrandId());
                saveWhsInfo.setWhsNm(entity.getStoreNm());
                saveWhsInfo.setWhsDvsn("W02");
                saveWhsInfo.setMgrNm(entity.getOwnerNm());
                saveWhsInfo.setMgrTelNo(entity.getTelNo());
                saveWhsInfo.setZipNo(entity.getZipNo());
                saveWhsInfo.setAddr1(entity.getAddr1());
                saveWhsInfo.setAddr2(entity.getAddr2());
                saveWhsInfo.setStoreId(entity.getStoreId());
                if ("N".equals(entity.getWhsUseYn())) {
                    saveWhsInfo.setWhsStCd("W003");
                } else {
                    if ("ST01".equals(entity.getStoreStCd())) {
                        saveWhsInfo.setWhsStCd("W001");
                    } else if ("ST03".equals(entity.getStoreStCd())) {
                        saveWhsInfo.setWhsStCd("W003");
                    } else {   //ST02
                        saveWhsInfo.setWhsStCd("W002");
                    }
                }

                //창고 로케이션 정보
                WhsMgntBaseLocEntity locEntity = new WhsMgntBaseLocEntity();
                locEntity.setLocation("1001");
                locEntity.setLocationNm(entity.getStoreNm());
                locEntity.setBrandId(entity.getBrandId());
                locEntity.setStckDvsn("SD01");

                if ("N".equals(entity.getWhsUseYn())) {
                    locEntity.setLocStCd("LOC003");
                } else {
                    if ("ST01".equals(entity.getStoreStCd())) {
                        locEntity.setLocStCd("LOC001");
                    } else if ("ST03".equals(entity.getStoreStCd())) {
                        locEntity.setLocStCd("LOC003");
                    } else {   //ST02
                        locEntity.setLocStCd("LOC002");
                    }
                }

                whsMngService.addStoreWhsInfo(userId,saveWhsInfo, locEntity );

            } else if ("U".equals(saveStoreInfolRequest.getViewCd())) {

                StoreBaseInfoEntity oldStoreInfo = storeBaseInfoMapper.selectStoreLoanInfo(entity.getBrandId(), entity.getStoreId()) ;
                String newLoanNo = "";
                if (!oldStoreInfo.getLoanDvsn().equals(entity.getLoanDvsn())) {
                    newLoanNo = fnGetDealNo(29,"");  // 신규 여신번호 생성
                    entity.setLoanMgntUnqNo(newLoanNo);
                }

                storeBaseInfoMapper.updateStoreInfo(userId, entity);

                UserMngEntity userUEntity = new UserMngEntity();
                userUEntity.setUserId(entity.getStoreId());
                userUEntity.setTelNo(entity.getTelNo());
                userUEntity.setEmail(entity.getEmalAddr());

                if ("ST01".equals(entity.getStoreStCd())) {
                    userUEntity.setUserStatCd("10");
                } else if ("ST03".equals(entity.getStoreStCd())) {
                    userUEntity.setUserStatCd("90");
                } else {   //ST02
                    userUEntity.setUserStatCd("30");
                }
                userMngMapper.updateUserInfo(userId, userUEntity);


                // 창고정보 변동 처리  whs_use_yn
               String whsStCd = "";
               String locStCd = "";
               String whschk = "1";

                if ("ST03".equals(entity.getStoreStCd())) {
                    // 매장 폐점  == > 매장창고 폐점 처리함
                    whsStCd = "W003";
                    whschk = "2";
                } else {
                    if (!oldStoreInfo.getWhsUseYn().equals(entity.getWhsUseYn())) {
                        if ("Y".equals(entity.getWhsUseYn())) {
                            whsStCd = "W001";
                            locStCd = "LOC001";
                        } else {
                            whsStCd = "W003";
                            locStCd = "LOC003";
                        }
                        whschk = "2";
                    }
                }

                if ("2".equals(whschk)) {
                    // 창고정보 업데이트
                    whsMngService.chgStatusStoreWhsInfo(userId, entity.getBrandId(), entity.getStoreId(), whsStCd, locStCd);
                }


                //여신정보 변동 발생시 처리
                if (oldStoreInfo.getLoanDvsn().equals(entity.getLoanDvsn())) {
                    //한도변경여부 확인
                    if (!oldStoreInfo.getLimitAmt().equals(entity.getLimitAmt())) {
                        // 한도금액 업데이트
                        LoanInfoEntity loanInfoUEntity = new LoanInfoEntity();
                        loanInfoUEntity.setLoanMgntUnqNo(entity.getLoanMgntUnqNo());
                        loanInfoUEntity.setLoanDvsn(entity.getLoanDvsn());
                        if ("LD02".equals(entity.getLoanDvsn())) {  // 후불
                            loanInfoUEntity.setCredtLimitAmt(entity.getLimitAmt());
                            loanInfoUEntity.setChrgeLimitAmt(0);
                            if (entity.getLimitAmt() > 0 ) {
                                loanInfoUEntity.setCredtLimitUseYn("Y");
                            } else {
                                loanInfoUEntity.setCredtLimitUseYn("N");
                            }
                        } else if ("LD01".equals(entity.getLoanDvsn())) {  // 선불
                            loanInfoUEntity.setCredtLimitAmt(0);
                            loanInfoUEntity.setChrgeLimitAmt(entity.getLimitAmt());
                            loanInfoUEntity.setCredtLimitUseYn("N");
                        } else if ("LD03".equals(entity.getLoanDvsn())) {  // 무정산
                            loanInfoUEntity.setCredtLimitAmt(0);
                            loanInfoUEntity.setChrgeLimitAmt(0);
                            loanInfoUEntity.setCredtLimitUseYn("N");
                        }
                        loanMgntMapper.updateLoanChgLimitInfo(userId, loanInfoUEntity);
                    }
                } else {
                    //이전거 사용종료 이력 남김.. 신규 loan 생성
                    LoanInfoEntity loanInfoChEntity = new LoanInfoEntity();
                    loanInfoChEntity.setNewLoanMgntUnqNo(newLoanNo);
                    loanInfoChEntity.setLoanMgntUnqNo(oldStoreInfo.getLoanMgntUnqNo());
                    loanInfoChEntity.setLoanDvsn(entity.getLoanDvsn());
                    if ("LD02".equals(entity.getLoanDvsn())) {
                        loanInfoChEntity.setCredtLimitAmt(entity.getLimitAmt());
                        loanInfoChEntity.setChrgeLimitAmt(0);
                        if (entity.getLimitAmt() > 0 ) {
                            loanInfoChEntity.setCredtLimitUseYn("Y");
                        } else {
                            loanInfoChEntity.setCredtLimitUseYn("N");
                        }
                    } else if ("LD01".equals(entity.getLoanDvsn())) {
                        loanInfoChEntity.setCredtLimitAmt(0);
                        loanInfoChEntity.setChrgeLimitAmt(entity.getLimitAmt());
                        loanInfoChEntity.setCredtLimitUseYn("N");
                    } else if ("LD03".equals(entity.getLoanDvsn())) {
                        loanInfoChEntity.setCredtLimitAmt(0);
                        loanInfoChEntity.setChrgeLimitAmt(0);
                        loanInfoChEntity.setCredtLimitUseYn("N");
                    }
                    //신규 생성
                    loanMgntMapper.insertAddLoanMgntInfo(userId, loanInfoChEntity) ;
                    // 기존거 종료
                    loanMgntMapper.updateLoanMgntCloseInfo(userId, oldStoreInfo.getLoanMgntUnqNo());

                }
            }

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



    /*
   매장 로그인 pw 초기화
   */
    @Transactional
    public String updateInitUserPw(String brandId, String storeId) throws Exception {
        // 사용자 정보를 가져옴
        try {
            String initPw  = storeBaseInfoMapper.selectStoreInitPw(brandId, storeId);
            String password = passwordEncoder.encode(initPw);
            userMngMapper.updateInitUserPw(storeId, password);
            return password;
        } catch (GlobalException e) {
            e.getStackTrace();
            throw new GlobalException(e.getSystemMessageCode());
        } catch (Exception e) {
            e.getStackTrace();
            throw new RuntimeException();
        }
    }

}
