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.BrandEntity;
import com.oqpo.api.entity.stinfo.StoreBaseInfoEntity;
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.web.dto.request.GridRequest;
import com.oqpo.api.web.dto.request.stinfo.brand.SaveBrandInfolRequest;
import com.oqpo.api.web.dto.request.stinfo.store.SaveStoreInfolRequest;
import com.oqpo.api.web.dto.response.GridResponse;
import com.oqpo.api.web.dto.response.stinfo.brand.AfflBrandSearchResponse;
import com.oqpo.api.web.dto.response.stinfo.brand.BrandInfoResponse;
import com.oqpo.api.web.dto.response.stinfo.brand.BrandSearchListResponse;
import com.oqpo.api.web.dto.response.stinfo.brand.BrandSearchResponse;
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.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 LoanMgntMapper loanMgntMapper;




    /*
      팝업 매장 리스트 조회
     */
    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().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.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.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");
                //패스워드 암호화
                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");
                        }
                }
                loanInfoEntity.setUseAmtTotal(0);
                loanInfoEntity.setTmpRcvAcctTotal(0);
                loanInfoEntity.setUseYn("Y");
                loanInfoEntity.setLoanDesc("신규 매장생성");

                loanMgntMapper.insertLoanMgntInfo(userId, loanInfoEntity);

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

                //여신정보 변동 발생시 처리
                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");
                        }
                        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");
                    }
                    //신규 생성
                    loanMgntMapper.insertAddLoanMgntInfo(userId, loanInfoChEntity) ;
                    // 기존거 종료
                    loanMgntMapper.updateLoanMgntCloseInfo(userId, oldStoreInfo.getLoanMgntUnqNo());

                }
            }

        } catch (GlobalException e) {
            e.getStackTrace();
            throw new GlobalException(e.getSystemMessageCode());
        } catch (Exception e) {
            e.getStackTrace();
            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();
        }
    }

}
