package kr.co.uplus.ez.api.custMgt;

import kr.co.uplus.ez.api.custMgt.dto.*;
import kr.co.uplus.ez.common.components.HubeasyApiComponents;
import kr.co.uplus.ez.common.data.*;
import kr.co.uplus.ez.common.utils.CommonUtils;
import kr.co.uplus.ez.common.utils.DateUtil;
import kr.co.uplus.ez.common.utils.DateUtils;
import kr.co.uplus.ez.common.utils.EncryptionUtil;
import kr.co.uplus.ez.common.utils.TextUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.mybatis.spring.SqlSessionTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.validation.Valid;

@Service
public class CustMgtService {

    private static final Logger logger = LoggerFactory.getLogger(CustMgtService.class);

    @Autowired
    @Qualifier("sqlSessionTemplateDb1")
    private SqlSessionTemplate sqlSessionMaster;

    @Autowired
    @Qualifier("sqlSessionTemplateDb2")
    private SqlSessionTemplate sqlSessionSlave;

    @Autowired
    private HubeasyApiComponents hubeasyApi;
    
    @Value("${limitCnt: 12}")
	private int limitCnt;
    
    
    /**
     * 요금제.
     */
    @Value("${testId.prodCd}")
    private String prodCd;
    /**
     * 생년월일.
     */
    @Value("${testId.rpsnBday}")
    private String rpsnBday;
    /**
     * 사업자번호.
     */
    @Value("${testId.brno}")
    private String brno;
    /**
     * 법인번호.
     */
    @Value("${testId.cono}")
    private String cono;
    /**
     * 우편번호.
     */
    @Value("${testId.zipCd}")
    private String zipCd;
    /**
     * 주소.
     */
    @Value("${testId.badr}")
    private String badr;
    /**
     * 상세주소.
     */
    @Value("${testId.dadr}")
    private String dadr;
    /**
     * 회사명.
     */
    @Value("${testId.cmpyNm}")
    private String cmpyNm;
    /**
     * 청구방법.
     */
    @Value("${testId.paymMthd}")
    private String paymMthd;
    /**
     * 고객유형코드.
     */
    @Value("${testId.custTyCd}")
    private String custTyCd;

    @Value("${msghubez.homepage-url:https://mhez.uplus.co.kr}")
    private String mailTempleteHomeUrl;
    
    @Value("${msghubez.uri.homepageLogin:/auth/bo}")
    private String loginUri;
    
    @Value("${msghubez.authKey: bohubez!@#$%}")
    private String authKey;

    @Value("${msghubez.applicationId:EZ_ADMIN}")
    private String apiApplicationId;

    @Value("${mail.from:msghubez@lguplus.co.kr}")
    private String fromEmail;

    @Value("${mail.templeteCode:E0005}")
    private String templeteCode;
    
    public static final String YEAR_MONTH_DAY 	= "yyyyMMdd";
	public static final String WEB_REQ_ID 		= "WEB_REQ_ID";
    

    /**
     * date : 2022. 4. 25. auth : ckr desc : 청약 고객 정보 목록 조회
     *
     * @param subsListReqDto
     * @return subsListResDto
     */
    public SubsListResDto subsList(SubsListReqDto subsListReqDto) {

        CustMgtMapper custMgtMapper = sqlSessionSlave.getMapper(CustMgtMapper.class);

        String nowPage = String.valueOf(subsListReqDto.getPage());
        int totalCnt = custMgtMapper.selectSubsListTotalCnt(subsListReqDto);

        if (totalCnt == 0) {

            SubsListRes subsListRes = new SubsListRes();
            subsListRes.setList(new ArrayList<>());

            Paging paging = new Paging();
            paging.setPage(nowPage);
            paging.setTotalCnt(String.valueOf(totalCnt));
            subsListRes.setPaging(paging);

            return new SubsListResDto(ApiResponseCode.CM_NOT_FOUND, subsListRes);
        }

        int page = subsListReqDto.getPage();
        int pagePerRows = subsListReqDto.getPagePerRows();
        page = (page - 1) * pagePerRows;
        subsListReqDto.setPage(page);

        List<SubsList> subsLists = custMgtMapper.selectSubsLists(subsListReqDto);

        SubsListRes subsListRes = new SubsListRes();
        subsListRes.setList(subsLists);

        Paging paging = new Paging();
        paging.setPage(nowPage);
        paging.setTotalCnt(String.valueOf(totalCnt));
        subsListRes.setPaging(paging);

        return new SubsListResDto(ApiResponseCode.SUCCESS, subsListRes);
    }

    /**
     * date : 2022. 4. 25. auth : ckr desc : 청약 고객 정보 목록 엑셀 다운로드
     *
     * @param subsListExcelReqDto
     * @return subsListExcelResDto
     */
    public SubsListExcelResDto subsListExcel(SubsListExcelReqDto subsListExcelReqDto) {

        CustMgtMapper custMgtMapper = sqlSessionSlave.getMapper(CustMgtMapper.class);

        SubsListRes subsListRes = new SubsListRes();
        // 청약 고객 정보 엑셀 조회.
        List<SubsList> subsLists = custMgtMapper.selectSubsListsExcel(subsListExcelReqDto);

        //
        Paging paging = new Paging();
        paging.setTotalCnt(String.valueOf(subsLists.size()));
        subsListRes.setPaging(paging);
        subsListRes.setList(subsLists);

        // 성공 응답.
        return new SubsListExcelResDto(ApiResponseCode.SUCCESS, subsListRes);
    }

    /**
     * date : 2022. 4. 25. auth : ckr desc : 청약 정보 상세 조회
     *
     * @param subsDetailReqDto
     * @return subsDetailResDto
     */
    public SubsDetailResDto subsDetail(SubsDetailReqDto subsDetailReqDto) {

        CustMgtMapper custMgtMapper = sqlSessionSlave.getMapper(CustMgtMapper.class);

        // 청약정보 상세조회.
        SubsDetail subsDetail = custMgtMapper.selectSubsDetailInfo(subsDetailReqDto);

        // 조회 결과 없음.
        if (subsDetail == null) {
            return new SubsDetailResDto(ApiResponseCode.CM_NOT_FOUND);
        }

        // 성공 응답.
        return new SubsDetailResDto(ApiResponseCode.SUCCESS, subsDetail);
    }

    /**
     * date : 2022. 4. 25. auth : ckr desc : 관리자명 조회
     *
     * @param adminInfoReqDto
     * @return adminInfoResDto
     */
    public AdminInfoResDto adminInfo(AdminInfoReqDto adminInfoReqDto) {

        CustMgtMapper custMgtMapper = sqlSessionSlave.getMapper(CustMgtMapper.class);

        ImUser param = new ImUser();
        param.setLoginId(adminInfoReqDto.getAdminId());
        // 마당ID 정보 조회.
        ImUser imUser = custMgtMapper.selectImUser(param);

        // 조회 결과 없음.
        if (imUser == null) {
            return new AdminInfoResDto(ApiResponseCode.CM_NOT_FOUND);
        }

        AdminInfo adminInfo = new AdminInfo();
        adminInfo.setAdminId(imUser.getLoginId());
        adminInfo.setAdminCd(imUser.getUserCode());
        adminInfo.setAdminNm(imUser.getName());
        // TODO 대리점명 확인 필요.
        adminInfo.setAgencyNm(imUser.getName());

        // 성공 응답.
        return new AdminInfoResDto(ApiResponseCode.SUCCESS, adminInfo);
    }

    /**
     * date : 2022. 4. 25. auth : ckr desc : 관리자ID,관리자명 수정
     *
     * @param adminInfoReqDto
     * @return updateAdminInfoResDto
     */
    public UpdateAdminInfoResDto updateAdminInfo(UpdateAdminInfoReqDto adminInfoReqDto) {
    	
    	logger.info("call 청약정보 수정, param ={}",adminInfoReqDto);
        CustMgtMapper custMgtMapper = sqlSessionMaster.getMapper(CustMgtMapper.class);

        SubsDetail subsDetail = new SubsDetail();
        subsDetail.setAdminId(adminInfoReqDto.getAdminId());
        subsDetail.setAdminNm(adminInfoReqDto.getAdminNm());
        subsDetail.setServiceId(adminInfoReqDto.getServiceId());
        subsDetail.setBindDcYn(adminInfoReqDto.getBindDcYn());
        subsDetail.setStat(adminInfoReqDto.getStat());
        subsDetail.setEntrNo(adminInfoReqDto.getSubsNo());
        
        

		try {
			custMgtMapper.updateAdminInfo(subsDetail);
	
			//청약상태가 유큐브 개통 상태일 시에만 수정 가능
			if("유큐브개통".equals(subsDetail.getStat())) {
				custMgtMapper.updateBindDcYn(subsDetail);
				logger.info("결합여부 수정. ID={}, 결합여부 ={}, 청약상태 ={}",subsDetail.getAdminId(),subsDetail.getBindDcYn(),subsDetail.getStat());
			}
		} catch (Exception e) {
			logger.info(e.toString());
			// TODO: handle exception
			return new UpdateAdminInfoResDto(ApiResponseCode.CM_DB_QUERY_ERR);
		}

        // 성공 응답.
        return new UpdateAdminInfoResDto(ApiResponseCode.SUCCESS);

    }

    /**
     * date : 2022. 4. 25. auth : ckr desc : 이월금액 목록 조회
     *
     * @param carryOverListReqDto
     * @return carryOverListResDto
     */
    public CarryOverListResDto carryOverList(CarryOverListReqDto carryOverListReqDto) {

        CustMgtMapper custMgtMapper = sqlSessionSlave.getMapper(CustMgtMapper.class);

        // 이월 금액 조회.
        carryOverListReqDto.setLimitCnt(limitCnt);
        List<CarryOver> carryOvers = custMgtMapper.selectCarryOverList(carryOverListReqDto);

        // 조회 결과 없음.
        if (carryOvers == null) {
            return new CarryOverListResDto(ApiResponseCode.CM_NOT_FOUND);
        }

        // 성공 응답.
        return new CarryOverListResDto(ApiResponseCode.SUCCESS,
                new CarryOverListRes(carryOvers, String.valueOf(carryOvers.size())));
    }

    /**
     * date : 2022. 4. 25. auth : ckr desc : 회원목록조회
     *
     * @param memberListReqDto
     * @return memberListResDto
     */
    public MemberListResDto memberList(MemberListReqDto memberListReqDto) {

        CustMgtMapper custMgtMapper = sqlSessionSlave.getMapper(CustMgtMapper.class);

        String nowPage = String.valueOf(memberListReqDto.getPage());
        int totalCnt = custMgtMapper.selectSvcUserListTotalCnt(memberListReqDto);

        if (totalCnt == 0) {

            MemberListRes memberListRes = new MemberListRes();
            memberListRes.setList(new ArrayList<>());

            Paging paging = new Paging();
            paging.setPage(nowPage);
            paging.setTotalCnt(String.valueOf(totalCnt));
            memberListRes.setPaging(paging);

            return new MemberListResDto(ApiResponseCode.CM_NOT_FOUND, memberListRes);
        }

        int page = memberListReqDto.getPage();
        int pagePerRows = memberListReqDto.getPagePerRows();
        page = (page - 1) * pagePerRows;
        memberListReqDto.setPage(page);

        List<MemberList> members = custMgtMapper.selectSvcUserList(memberListReqDto);

        MemberListRes memberListRes = new MemberListRes();
        memberListRes.setList(members);

        Paging paging = new Paging();
        paging.setPage(nowPage);
        paging.setTotalCnt(String.valueOf(totalCnt));
        memberListRes.setPaging(paging);

        return new MemberListResDto(ApiResponseCode.SUCCESS, memberListRes);
    }

    /**
     * date : 2022. 4. 25. auth : ckr desc : 회원 정보 상세 조회
     *
     * @param memberDetailReqDto
     * @return MemberDetailResDto
     */
    @SuppressWarnings("unused")
	public MemberDetailResDto memberDetail(MemberDetailReqDto memberDetailReqDto) {

        CustMgtMapper custMgtMapper = sqlSessionSlave.getMapper(CustMgtMapper.class);

        MemberDetailRes memberDetailRes = custMgtMapper.selectMemberDetail(memberDetailReqDto);
        memberDetailRes.setHomePageUrl(mailTempleteHomeUrl+loginUri);
        memberDetailRes.setAuthKey(authKey);
        
        // 조회 결과 없음.
        if (memberDetailRes == null) {
            return new MemberDetailResDto(ApiResponseCode.CM_NOT_FOUND);
        }

        return new MemberDetailResDto(ApiResponseCode.SUCCESS, memberDetailRes);
    }

    /**
     * 사용자 상세 리스트 조회.
     *
     * @param memberAdminDetailReqDto
     * @return MemberDetailListResDto
     */
    public MemberAdminDetailResDto memberAdminDetail(MemberAdminDetailReqDto memberAdminDetailReqDto) {

        CustMgtMapper custMgtMapper = sqlSessionSlave.getMapper(CustMgtMapper.class);

        MemberAdminDetailRes memberAdminDetailRes = custMgtMapper.selectMemberAdminDetail(memberAdminDetailReqDto);

        // 조회 결과 없음.
        if (memberAdminDetailRes == null) {
            return new MemberAdminDetailResDto(ApiResponseCode.CM_NOT_FOUND);
        }

        memberAdminDetailRes.setHomePageUrl(mailTempleteHomeUrl+loginUri);
        memberAdminDetailRes.setAuthKey(authKey);
        
        String nowPage = String.valueOf(memberAdminDetailReqDto.getPage());

        int totalCnt = custMgtMapper.selectMemberDetailListTotalCnt(memberAdminDetailReqDto);

        if (totalCnt == 0) {
            memberAdminDetailRes.setList(new ArrayList<>());

            Paging paging = new Paging();
            paging.setPage(nowPage);
            paging.setTotalCnt(String.valueOf(totalCnt));
            memberAdminDetailRes.setPaging(paging);

        } else {
            int page = memberAdminDetailReqDto.getPage();
            int pagePerRows = memberAdminDetailReqDto.getPagePerRows();
            page = (page - 1) * pagePerRows;
            memberAdminDetailReqDto.setPage(page);

            Paging paging = new Paging();
            paging.setPage(nowPage);
            paging.setTotalCnt(String.valueOf(totalCnt));
            memberAdminDetailRes.setPaging(paging);

            List<MemberDetail> memberDetails = custMgtMapper.selectMemberDetailList(memberAdminDetailReqDto);
            memberAdminDetailRes.setList(memberDetails);
        }

        return new MemberAdminDetailResDto(ApiResponseCode.SUCCESS, memberAdminDetailRes);
    }

    /**
     * date : 2022. 4. 25. auth : ckr desc : 테스트ID 등록
     *
     * @param insertTestIdReqDto
     * @return
     */
    @Transactional(value="db1TransactionManager")
    public InsertTestIdResDto insertTestId(InsertTestIdReqDto insertTestIdReqDto){

		CustMgtMapper custMgtMapper = sqlSessionMaster.getMapper(CustMgtMapper.class);

        int getUserIdCount = custMgtMapper.getUserIdCount(insertTestIdReqDto.getUserId());

        // 이미 존재하는 아이디.
        if (getUserIdCount > 0) {
            return new InsertTestIdResDto(ApiResponseCode.CE_DUPLICATE_ID);
        }
        
        // 1. 사업자 번호로 조회.
        int checkCustInfo = custMgtMapper.selectCustInfoCount(brno);
        String custSeq = custMgtMapper.getCustSeq(brno);

        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        UserDetails userDetails = (UserDetails) principal;
        String regId = userDetails.getUsername();
        
        if (checkCustInfo < 1) {
            // 1-2. 사업자 번호로 미존재시 : 고객정보 등록.
            CustInfo custInfo = new CustInfo();
            custInfo.setCustSeq(custSeq);
            custInfo.setBizrno(brno);
            custInfo.setCustNm(cmpyNm);
            custInfo.setCustTyCd(custTyCd);
            custInfo.setCorpno(cono);
            custInfo.setReprNm(insertTestIdReqDto.getUserNm());
            custInfo.setBrthdy(rpsnBday);
            custInfo.setZipcd(zipCd);
            custInfo.setAddr1(badr);
            custInfo.setAddr2(dadr);
            custInfo.setRegId(regId);
            custInfo.setChgId(regId);
            // 고객정보 등록.
            custMgtMapper.insertCustInfo(custInfo);
        }

        // 2. 서비스 이용자 등록.
        String userSeq = custMgtMapper.getUserSeq();
        SvcUserInfo svcUserInfo = new SvcUserInfo();
        svcUserInfo.setUserSeq(userSeq);
        svcUserInfo.setUserId(insertTestIdReqDto.getUserId());
        svcUserInfo.setUserNm(insertTestIdReqDto.getUserNm());
        svcUserInfo.setUserSttusCd(Const.USER_STTUS_CD_NOMAL);
        svcUserInfo.setCustSeq(custSeq);
        svcUserInfo.setUserTpCd(Const.USER_TP_CD_TEST);
        svcUserInfo.setPrntsUserSeq(userSeq);
        svcUserInfo.setPwd(insertTestIdReqDto.getUserPw());
        svcUserInfo.setBizrAuthYn(Const.COMM_NO);
        svcUserInfo.setLineTpCd(Const.LINE_TP_CD_NORMAL);
        svcUserInfo.setHpNo(insertTestIdReqDto.getMdn());
        svcUserInfo.setEmail(insertTestIdReqDto.getUserEmail());
        svcUserInfo.setAuthcd080(custMgtMapper.getAuth080());
        svcUserInfo.setAutCd(Const.USER_AUTCD_ADM);
        svcUserInfo.setRegId(regId);
        svcUserInfo.setChgId(regId);

        // 서비스 이용자 등록.
        custMgtMapper.insertSvcUserInfo(svcUserInfo);

        // 3. 청약정보 등록
        SubsInfo subsInfo = new SubsInfo();
        String subId = custMgtMapper.getSubId();
        subsInfo.setSubsId(subId);
        String entrNo = custMgtMapper.getEntrNo();
        subsInfo.setEntrNo(entrNo);
        subsInfo.setUserSeq(userSeq);
        subsInfo.setCustSeq(custSeq);
        subsInfo.setSubsSttusCd(Const.SUBS_STTUS_CD_NORMAL);
        subsInfo.setProdCd(prodCd);
        subsInfo.setBindDcYn(Const.COMM_NO);
        subsInfo.setRegId(regId);
        subsInfo.setChgId(regId);

        // 청약정보 등록.
        custMgtMapper.insertSubsInfo(subsInfo);
        
        // 청약상태_이력 테이블 개통 이력 insert        
        Date now = new Date();
		String subsDt = DateUtils.dateToStr(now, "yyyyMMddHHmmss");        
 		SbscstHstDto newSbscstHst = new SbscstHstDto();
 		newSbscstHst.setSubsId(subId);												// 청약ID		
 		newSbscstHst.setEfctStDt(subsDt);					                        // 유효 종료 일시 		
 		newSbscstHst.setProdCd(prodCd);                       						// 상품 코드
 		newSbscstHst.setSubsSttusCd(Const.SUBS_STTUS_CD_NORMAL);                    // 청약 상태 코드
 		newSbscstHst.setRegId(regId);	                   						    // 변경 ID
 		// 청약 이력 등록
 		custMgtMapper.insertSbscstHst(newSbscstHst);
 		
 		// 1. 한도 초기화		
		// 1-1. 상품금액 조회
 		ProdInfo prodInfo = new ProdInfo();
		prodInfo = custMgtMapper.getProdAmt(userSeq);		
		String prodAmt = prodInfo.getProdAmt();
		
		
		// 1-2. 오더 채번
		String order = custMgtMapper.getOrder();		
		String orderCretDt = order.substring(0,12);
		
		// 1-3. 오더 추가
		OrderDto orderDto = new OrderDto();
		orderDto.setOrderId(order);
		orderDto.setOrderCretDt(orderCretDt);
		orderDto.setOrderTyCd(Const.ORDER_TYPE_CD_03);		// 한도초기화 하기 위한 주문 유형 코드 (01:발송차감, 02:차감결과처리, 03:한도초기화, 04:이월금소멸)
		orderDto.setRegId(regId);	
		custMgtMapper.insertOrder(orderDto);
				
		// 1-4. 차감 상세 INSERT
		LmtdctDtlDto lmtdctDtlDto = new LmtdctDtlDto();
		lmtdctDtlDto.setOrderCretDt(orderCretDt);                           // 오더 생성일시
		lmtdctDtlDto.setUserSeq(userSeq);					                // 이용자 일련번호
		String lmtYm = subsDt.substring(0,6);                                
		lmtdctDtlDto.setLmtYm(lmtYm);                                       // 한도 년월
		lmtdctDtlDto.setUseYm(lmtYm);                                       // 사용 년월
		lmtdctDtlDto.setLmtTpCd(Const.LMTDCT_DTL_TYPE_CD_01);               // 한도 유형 코드
		lmtdctDtlDto.setDdctTpcd(Const.LMTDCT_DTL_DDCT_TYPE_CD_04);         // 차감 유형 코드
		lmtdctDtlDto.setDdctAmt(prodAmt);                                   // 차감 금액
		lmtdctDtlDto.setExeOrderId(order);                                  // 실행 오더 ID
		lmtdctDtlDto.setSnddctOrderId(order);                               // 발송 차감 오더 ID
		lmtdctDtlDto.setRegId(regId);										// 등록 ID
		
		custMgtMapper.insertLmtdctDtl(lmtdctDtlDto);
		
		// 1-5. 한도 INSERT
		UserLmtDto userLmtDto = new UserLmtDto();
		userLmtDto.setUserSeq(userSeq);										// 이용자 일련번호
		userLmtDto.setLmtYm(lmtYm);                                         // 한도 년월
		userLmtDto.setFxLmtAmt(prodAmt);                                    // 정액 한도 금액
		userLmtDto.setMrtLmtAmt(prodAmt);                                   // 종량 한도 금액
		userLmtDto.setFxBlnc(prodAmt);                                      // 정액 잔액
		userLmtDto.setRegId(regId);							                // 등록자ID
		userLmtDto.setChgId(regId);                							// 변경자ID		
		
		custMgtMapper.insertUserLmt(userLmtDto);
				
        return new InsertTestIdResDto(ApiResponseCode.SUCCESS);
    }

    /**
     * date : 2022. 4. 25. auth : ckr desc : 전체 메모 목록 조회
     *
     * @param allMemoListReqDto
     * @return AllMemoListResDto
     */
    public AllMemoListResDto allMemoList(AllMemoListReqDto allMemoListReqDto) {

        CustMgtMapper custMgtMapper = sqlSessionSlave.getMapper(CustMgtMapper.class);

        String nowPage = String.valueOf(allMemoListReqDto.getPage());
        int totalCnt = custMgtMapper.selectMemoListTotalCnt(allMemoListReqDto);

        if (totalCnt == 0) {

            AllMemoListRes allMemoListRes = new AllMemoListRes();
            allMemoListRes.setList(new ArrayList<>());

            Paging paging = new Paging();
            paging.setPage(nowPage);
            paging.setTotalCnt(String.valueOf(totalCnt));
            allMemoListRes.setPaging(paging);

            return new AllMemoListResDto(ApiResponseCode.CM_NOT_FOUND, allMemoListRes);
        }

        int page = allMemoListReqDto.getPage();
        int pagePerRows = allMemoListReqDto.getPagePerRows();
        page = (page - 1) * pagePerRows;
        allMemoListReqDto.setPage(page);

        List<AllMemoList> allMemoLists = custMgtMapper.selectMemoList(allMemoListReqDto);

        AllMemoListRes allMemoListRes = new AllMemoListRes();
        allMemoListRes.setList(allMemoLists);

        Paging paging = new Paging();
        paging.setPage(nowPage);
        paging.setTotalCnt(String.valueOf(totalCnt));
        allMemoListRes.setPaging(paging);

        return new AllMemoListResDto(ApiResponseCode.SUCCESS, allMemoListRes);
    }

    /**
     * date : 2022. 4. 25. auth : ckr desc : 메모 삭제
     *
     * @param deleteMemoReqDto
     * @return
     */
    public DeleteMemoResDto deleteMemo(DeleteMemoReqDto deleteMemoReqDto) {

        CustMgtMapper custMgtMapper = sqlSessionMaster.getMapper(CustMgtMapper.class);

        // 1. 회원정보 조회.

        // user_seq 이용자일련번호
        int checkUserSeq = custMgtMapper.selectUserSeq(deleteMemoReqDto.getUserId());

        if (checkUserSeq < 1) {
            return new DeleteMemoResDto(ApiResponseCode.CM_NOT_FOUND);
        }

        // 2. 메모 삭제.
        // seqNo, userSeq를 담음.
        Map<String, Object> MemoParamMap = new HashMap<String, Object>();
        MemoParamMap.put("seqNo", deleteMemoReqDto.getSeqNo());
        MemoParamMap.put("userSeq", checkUserSeq);

        try {
            // 삭제한 건수가 나옴.
            int result = custMgtMapper.deleteMemo(MemoParamMap);
            // 한건이 나오지 않을경우
            if (result < 1) {
                return new DeleteMemoResDto(ApiResponseCode.CM_NOT_FOUND);
            }
        } catch (Exception e) {
            return new DeleteMemoResDto(ApiResponseCode.CM_DB_QUERY_ERR);
        }

        return new DeleteMemoResDto(ApiResponseCode.SUCCESS);
    }

    /**
     * date : 2022. 4. 25. auth : ckr desc : 사용자 정보 등록
     *
     * @param insertUserReqDto
     * @return
     */   
    public InsertUserResDto insertUser(InsertUserReqDto insertUserReqDto) {
        CustMgtMapper custMgtMapper = sqlSessionMaster.getMapper(CustMgtMapper.class);
        Map<Object, Object> mailReqMap = new HashMap<Object, Object>();
        Map<Object, Object> mailResultMap = new HashMap<Object, Object>();

        // 임시패스워드 평문 생성
        String imsiPw = RandomStringUtils.randomAlphanumeric(10);

        String userId = insertUserReqDto.getUserId();
        int userCnt = 0;

        try {
            userCnt = custMgtMapper.getUserIdCount(userId);
            if (userCnt > 0) {
                return new InsertUserResDto(ApiResponseCode.CE_DUPLICATE_ID);
            }

            // 패스워드 암호화
            String encPwd = EncryptionUtil.getCustomSHA512(userId, imsiPw);
            insertUserReqDto.setUserPw(encPwd);

            // 사용자 정보 등록
            custMgtMapper.insertUserInfo(insertUserReqDto);

            // API authToken 조회
            String apiAuthToken = custMgtMapper.selectApiAuthToken(apiApplicationId);

            // 임시패스워드(평문) 이메일 발송처리
            mailReqMap.put("applicationId", apiApplicationId);
            mailReqMap.put("authToken", apiAuthToken);
            mailReqMap.put("userId", userId);
            mailReqMap.put("tmpPwd", imsiPw);
            mailReqMap.put("toEmail", insertUserReqDto.getUserEmail());
            mailReqMap.put("fromEmail", fromEmail);
            mailReqMap.put("templeteCode", templeteCode);
            mailReqMap.put("homeUrl", mailTempleteHomeUrl);

            logger.debug("############## [Email Send Start] ###############");
            logger.debug("[Email Send Request - applicationId : {}]", mailReqMap.get("applicationId"));
            logger.debug("[Email Send Request - authToken : {}]", mailReqMap.get("authToken"));
            logger.debug("[Email Send Request - userId : {}]", mailReqMap.get("userId"));
            logger.debug("[Email Send Request - tmpPwd : {}]", mailReqMap.get("tmpPwd"));
            logger.debug("[Email Send Request - toEmail : {}]", mailReqMap.get("toEmail"));
            logger.debug("[Email Send Request - fromEmail : {}]", mailReqMap.get("fromEmail"));
            logger.debug("[Email Send Request - templeteCode : {}]", mailReqMap.get("templeteCode"));
            logger.debug("[Email Send Request - homeUrl : {}]", mailReqMap.get("homeUrl"));

            mailResultMap = hubeasyApi.sendTemplateMailApi(mailReqMap);

            if (mailResultMap != null) {
                logger.debug("[Email Send API RESULT : {}]", mailResultMap.get("API_RSLT"));
                if ("F".equals(mailResultMap.get("API_RSLT"))) {
                    logger.debug("[Email Send API ERROR : {}]", mailResultMap.get("API_RSLT_MSG"));
                }
            }
            logger.debug("############## [Email Send End] ###############");

        } catch (Exception e) {
            logger.error(e.getMessage());
            return new InsertUserResDto(ApiResponseCode.CM_DB_QUERY_ERR);
        }

        return new InsertUserResDto(ApiResponseCode.SUCCESS);
    }

    /**
     * date : 2022. 4. 25. auth : ckr desc : 사용자 정보 수정
     *
     * @param updateUserReqDto
     * @return
     */
    public UpdateUserResDto updateUser(UpdateUserReqDto updateUserReqDto) {
        CustMgtMapper custMgtMapper = sqlSessionMaster.getMapper(CustMgtMapper.class);

        String userId = updateUserReqDto.getUserId();
        String userPw = updateUserReqDto.getUserPw();

        try {
            // 패스워드 암호화
            String encPwd = EncryptionUtil.getCustomSHA512(userId, userPw);
            updateUserReqDto.setUserPw(encPwd);

            // 사용자 정보 수정
            custMgtMapper.updateUserInfo(updateUserReqDto);


        } catch (Exception e) {
            return new UpdateUserResDto(ApiResponseCode.CM_DB_QUERY_ERR);
        }

        return new UpdateUserResDto(ApiResponseCode.SUCCESS);
    }

    /**
     * date : 2022. 4. 25. auth : ckr desc : 사용자ID 대량등록
     *
     * @param insertMassUserReqDto
     */
    public InsertMassUserResDto insertMassUser(InsertMassUserReqDto insertMassUserReqDto) {

        CustMgtMapper custMgtMapper = sqlSessionMaster.getMapper(CustMgtMapper.class);

        // 1. 관리자 ID 존재 여부 체크.
        SvcUserInfo svcUserInfo = custMgtMapper.selectSvcUserInfo(insertMassUserReqDto.getAdminId());

        if (svcUserInfo == null) {
            return new InsertMassUserResDto(ApiResponseCode.CM_NOT_FOUND);
        }

        // 1. ID 중복 체크.
        List<InsertMassUser> orgInsertMassUsers = insertMassUserReqDto.getList();
        List<InsertMassUser> errInsertMassUsers = new ArrayList<InsertMassUser>();
        List<InsertMassUser> insertMassUsers = new ArrayList<InsertMassUser>();

        for (int i = 0; i < orgInsertMassUsers.size(); i++) {

            InsertMassUser insertMassUser = orgInsertMassUsers.get(i);

            InsertUserReqDto insertUserReqDto = new InsertUserReqDto();
            insertUserReqDto.setUserId(insertMassUser.getUserId());
            int flag = custMgtMapper.selectUserInfoCnt(insertUserReqDto);

            if (flag == 0) {
                insertMassUsers.add(insertMassUser);
            } else {
                errInsertMassUsers.add(insertMassUser);
            }
        }

        // 이메일발송 API 사용을 위한 authToken 조회
        String apiAuthToken = custMgtMapper.selectApiAuthToken(apiApplicationId);
        Map<Object, Object> mailReqMap = new HashMap<Object, Object>();
        Map<Object, Object> mailResultMap = new HashMap<Object, Object>();

        InsertMassUserRes insertMassUserRes = new InsertMassUserRes();
        int successCnt = 0;
        for (int j = 0; j < insertMassUsers.size(); j++) {
            try {
                // DB 처리.
                String userId = insertMassUsers.get(j).getUserId();
                String imsiPw = RandomStringUtils.randomAlphanumeric(10);

                SvcUserInfo svcUserInfo2 = new SvcUserInfo();
                String userSeq = custMgtMapper.getUserSeq();

                svcUserInfo2.setUserSeq(userSeq);
                svcUserInfo2.setUserId(userId);
                svcUserInfo2.setUserNm(insertMassUsers.get(j).getUserNm());
                svcUserInfo2.setPwd(imsiPw);
                svcUserInfo2.setPwdInit(Const.COMM_YES);
                svcUserInfo2.setHpNo(insertMassUsers.get(j).getMdn());
                svcUserInfo2.setEmail(insertMassUsers.get(j).getEmail());
                if(StringUtils.contains(insertMassUsers.get(j).getStat(), "사용")){
                    svcUserInfo2.setUserSttusCd(Const.USER_STTUS_CD_NOMAL);
                }else{
                    svcUserInfo2.setUserSttusCd(Const.USER_STTUS_CD_STOP);
                }
                svcUserInfo2.setCustSeq(svcUserInfo.getCustSeq());
                svcUserInfo2.setPrntsUserSeq(svcUserInfo.getUserSeq());
                svcUserInfo2.setUserTpCd(Const.USER_TP_CD_USR);
                svcUserInfo2.setLineTpCd(svcUserInfo.getLineTpCd());
                svcUserInfo2.setRegId(userId);
                svcUserInfo2.setChgId(userId);

                custMgtMapper.insertSvcUserInfo(svcUserInfo2);

                successCnt++;

                // 임시비밀번호 이메일발송
                mailReqMap = new HashMap<Object, Object>();
                mailResultMap = new HashMap<Object, Object>();

                mailReqMap.put("applicationId", apiApplicationId);
                mailReqMap.put("authToken", apiAuthToken);
                mailReqMap.put("userId", userId);
                mailReqMap.put("tmpPwd", imsiPw);
                mailReqMap.put("toEmail", insertMassUsers.get(j).getEmail());
                mailReqMap.put("fromEmail", fromEmail);
                mailReqMap.put("templeteCode", templeteCode);
                mailReqMap.put("homeUrl", mailTempleteHomeUrl);

                logger.debug("############## [Email Send Start] ###############");
                logger.debug("[Email Send Request - applicationId : {}]", mailReqMap.get("applicationId"));
                logger.debug("[Email Send Request - authToken : {}]", mailReqMap.get("authToken"));
                logger.debug("[Email Send Request - userId : {}]", mailReqMap.get("userId"));
                logger.debug("[Email Send Request - tmpPwd : {}]", mailReqMap.get("tmpPwd"));
                logger.debug("[Email Send Request - toEmail : {}]", mailReqMap.get("toEmail"));
                logger.debug("[Email Send Request - fromEmail : {}]", mailReqMap.get("fromEmail"));
                logger.debug("[Email Send Request - templeteCode : {}]", mailReqMap.get("templeteCode"));
                logger.debug("[Email Send Request - homeUrl : {}]", mailReqMap.get("homeUrl"));

//                mailResultMap = hubeasyApi.sendTemplateMailApi(mailReqMap);
//
//                if (mailResultMap != null) {
//                    logger.debug("[Email Send API RESULT : {}]", mailResultMap.get("API_RSLT"));
//                    if ("F".equals(mailResultMap.get("API_RSLT"))) {
//                        logger.debug("[Email Send API ERROR : {}]", mailResultMap.get("API_RSLT_MSG"));
//                    }
//                }
                logger.debug("############## [Email Send End] ###############");

            } catch (Exception e) {
                errInsertMassUsers.add(insertMassUsers.get(j));
            }
        }

        // 요청건수.
//        insertMassUserRes.setTotalCnt(String.valueOf(insertMassUsers.size()));
        insertMassUserRes.setTotalCnt(String.valueOf(orgInsertMassUsers.size()));        
        // 성공건수.
        insertMassUserRes.setSuccessCnt(String.valueOf(successCnt));
        // 실패건수.
        insertMassUserRes.setFailCnt(String.valueOf(errInsertMassUsers.size()));

        InsertMassUserResDto result = new InsertMassUserResDto(ApiResponseCode.SUCCESS, insertMassUserRes);
        return result;
    }

    /**
     * date : 2022. 4. 25. auth : ckr desc : 사용자 정보 삭제
     *
     * @param deleteUserReqDto
     * @return
     */
    public DeleteUserResDto deleteUser(DeleteUserReqDto deleteUserReqDto) {
        CustMgtMapper custMgtMapper = sqlSessionMaster.getMapper(CustMgtMapper.class);

        // 1.관리자 정보 조회
//			String checkAdminId = custMgtMapper.selectAdminId(deleteUserReqDto.getAdminId());
//
//			//2. 관리자 정보 조회결과 응답 없음
//			if(checkAdminId == null) {
//				return new DeleteUserResDto(ApiResponseCode.CM_NOT_FOUND);
//			}

        try {
            // 3. 사용자정보 삭제
            int result = custMgtMapper.deleteUserList(deleteUserReqDto);

            // 4. 삭제대상이 없음.
            if (result < 1) {
                return new DeleteUserResDto(ApiResponseCode.CM_NOT_FOUND);
            }
        } catch (Exception e) {
            // 5. 그 이외의 결과가 나왔을때 데이터
            return new DeleteUserResDto(ApiResponseCode.CM_DB_QUERY_ERR);
        }
        // 6. 성공 응답.
        return new DeleteUserResDto(ApiResponseCode.SUCCESS);

    }

    /**
     * date : 2022. 4. 25. auth : ckr desc : 관리자 정보 수정
     *
     * @param paramMap
     * @return
     */
    public ApiResponseMessage updateMember(Map<String, Object> paramMap) {
        ApiResponseMessage result = new ApiResponseMessage(ApiResponseCode.SUCCESS);
        return result;
    }

    /**
     * date : 2022. 4. 25.
     * auth : ckr
     * desc : 관리자 정보(종합) 수정
     *
     * @param updateAdminInfoTotalReqDto
     * @return UpdateAdminInfoTotalResDto
     * @
     */
    public UpdateAdminInfoTotalResDto updateAdminInfoTotal(UpdateAdminInfoTotalReqDto updateAdminInfoTotalReqDto) {

        CustMgtMapper custMgtMapper = sqlSessionMaster.getMapper(CustMgtMapper.class);
        Map<String, Object> paramMap = new HashMap<String, Object>();
        Map<String, Object> rstAmtMap = new HashMap<String, Object>();
        try {
            // 1. 사용자 정보 update
            custMgtMapper.updateMemberInfo(updateAdminInfoTotalReqDto);

            // 2. 메모정보 insert
            if(StringUtils.isNotEmpty(updateAdminInfoTotalReqDto.getMemo())) {
            	custMgtMapper.insertMemo(updateAdminInfoTotalReqDto);            	
            }

            // 3. 발송 한도 update
            if (updateAdminInfoTotalReqDto.getSendingLimit() != null) {
                BigDecimal sendingLimitAmt = new BigDecimal(StringUtils.remove(updateAdminInfoTotalReqDto.getSendingLimit(), ","));

                paramMap.put("userId", updateAdminInfoTotalReqDto.getUserId());
                // 3-1. 기존 정액한도금액 조회
                rstAmtMap = custMgtMapper.selectAdminSendingLimt(paramMap);
                if (rstAmtMap != null) {
                    String stFxLmtAmt = rstAmtMap.get("fxLmtAmt").toString();
                    BigDecimal fxLmtAmt = new BigDecimal(stFxLmtAmt);

                    BigDecimal targetMrtLmtAmt = new BigDecimal(0);

                    // 변동요청발송한도금액이 기존정액한도금액보다 작으면 한도금액 변경 불가 실패처리
                    if (sendingLimitAmt.compareTo(fxLmtAmt) < 0) {
                        return new UpdateAdminInfoTotalResDto(ApiResponseCode.CE_SENDINGLIMT_ERROR);
                    }

                    // 3-2. 발송한도금액 수정(종량 한도금액 UPDATE)
                    // 변동요청발송한도금액 - 기존정액한도금액 = 변경할 종량한도금액
                    targetMrtLmtAmt = sendingLimitAmt.subtract(fxLmtAmt);
                    paramMap.put("sendingLimit", targetMrtLmtAmt);

                    custMgtMapper.updateAdminSendingLimit(paramMap);
                }
            }


        } catch (Exception e) {
            return new UpdateAdminInfoTotalResDto(ApiResponseCode.CM_DB_QUERY_ERR);
        }

        return new UpdateAdminInfoTotalResDto(ApiResponseCode.SUCCESS);
    }
    
    
    /**
     * date : 2022. 8. 31. 
     * auth : ckr 
     * desc : 사용자 ID 중복체크
     *
     * @param insertUserReqDto
     * @return
     */   
    public InsertUserResDto duplicateCheckUserId(InsertUserReqDto insertUserReqDto) {
        CustMgtMapper custMgtMapper = sqlSessionSlave.getMapper(CustMgtMapper.class);
        
        String userId = insertUserReqDto.getUserId();
        int userCnt = 0;
        userCnt = custMgtMapper.getUserIdCount(userId);
        if (userCnt > 0) {
        	logger.debug("사용자 ID 중복 : {}",userId);
            return new InsertUserResDto(ApiResponseCode.CE_DUPLICATE_ID);
        }
        
        return new InsertUserResDto(ApiResponseCode.SUCCESS);
    }

    /**
      * date : 2023. 3. 15.
	 * auth : won
	 * desc : 충전관리 목록 조회
	 * @param ChrgListReqDto
	 * @return ChrgListResDto
     */ 
	public ChrgListResDto chrgList(ChrgListReqDto chrgListReqDto) {
		CustMgtMapper custMgtMapper = sqlSessionMaster.getMapper(CustMgtMapper.class);
		
		String nowPage = String.valueOf(chrgListReqDto.getPage());
        int totalCnt = custMgtMapper.cntChrgList(chrgListReqDto);
        logger.debug("getStartDt={}",chrgListReqDto.getStartDt());
        if (totalCnt == 0) {

            ChrgListRes chrgListRes = new ChrgListRes();
            chrgListRes.setList(new ArrayList<>());

            Paging paging = new Paging();
            paging.setPage(nowPage);
            paging.setTotalCnt(String.valueOf(totalCnt));
            chrgListRes.setPaging(paging);

            return new ChrgListResDto(ApiResponseCode.CM_NOT_FOUND, chrgListRes);
        }
        
        int page = chrgListReqDto.getPage();
        int pagePerRows = chrgListReqDto.getPagePerRows();
        page = (page - 1) * pagePerRows;
        chrgListReqDto.setPage(page);
        
//        Date now = new Date();
//        String chrgYm = DateUtils.dateToStr(now, "yyyyMM");
        
		
		List<ChrgList> chrgList= custMgtMapper.selectChrgList(chrgListReqDto);

		
		
		for (int i = 0; i < chrgList.size(); i++) {
			String startDt = chrgList.get(i).getStrtYm();
			String endDt = chrgList.get(i).getEndYm();
			
			chrgList.get(i).setChrgDate(startDt + "~" +endDt);
		}
		
		ChrgListRes chrgListRes =  new ChrgListRes();
		chrgListRes.setList(chrgList);
		
		Paging paging = new Paging();
        paging.setPage(nowPage);
        paging.setTotalCnt(String.valueOf(totalCnt));
        chrgListRes.setPaging(paging);
        
		return new ChrgListResDto(ApiResponseCode.SUCCESS, chrgListRes);
	}

	/**
	 * date : 2023. 3. 15.
	 * auth : won
	 * desc : 충전관리 상세 조회
	 * @param ChrgDetailReqDto
	 * @return ChrgDetailResDto
	 */
	public ChrgDetailResDto chrgDetail(@Valid ChrgDetailReqDto chrgDetailReqDto) {
		CustMgtMapper custMgtMapper = sqlSessionSlave.getMapper(CustMgtMapper.class);
		
		ChrgDetail chrgDetail = custMgtMapper.selectChrgDetail(chrgDetailReqDto);
		
		if (chrgDetail == null) {
            return new ChrgDetailResDto(ApiResponseCode.CM_NOT_FOUND);
        }

        // 성공 응답.
        return new ChrgDetailResDto(ApiResponseCode.SUCCESS, chrgDetail);
	}
	
	/**
	 * * date : 2023. 3. 15.
	 * * auth : won
	 * * desc : 충전관리 등록
	 * @param paramMap
	 * @return
	 */
	@Transactional(value="db1TransactionManager")
	public InsertChrgResDto InsertChrg(@Valid InsertChrgReqDto insertChrgReqDto){
		CustMgtMapper custMgtMapper = sqlSessionMaster.getMapper(CustMgtMapper.class);
		
		int resultcnt = 0;
		
		// 1. 사용자 유무 확인
		int getUserIdCount = custMgtMapper.getUserIdCount(insertChrgReqDto.getUserId());
		
		if (getUserIdCount < 1) {
            return new InsertChrgResDto(ApiResponseCode.CM_NOT_FOUND);
        }
		
        // 3. 충전 정보 등록
        String chrgSeq = custMgtMapper.getChrgSeq();
        SvcUserInfo userInfo = custMgtMapper.selectUserInfo(insertChrgReqDto.getUserId());
        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        UserDetails userDetails = (UserDetails) principal;
        String regId = userDetails.getUsername();
        
        logger.debug("insertChrgReqDto= {}", insertChrgReqDto);
        
		ChrgInfo chrgInfo = new ChrgInfo();
		chrgInfo.setChrgSeq(chrgSeq);
		chrgInfo.setUserSeq(userInfo.getUserSeq());
		chrgInfo.setChrgDiv(insertChrgReqDto.getChrgDiv());
		String StrYm = insertChrgReqDto.getStrtYm().replace("-", "").substring(0, 6);
		chrgInfo.setStrtYm(StrYm);
		String EndYm = insertChrgReqDto.getEndYm().replace("-", "").substring(0, 6);
		chrgInfo.setEndYm(EndYm);
		chrgInfo.setChrgAmt(insertChrgReqDto.getChrgAmt());
		chrgInfo.setRegId(regId);		//로그인 ID
		chrgInfo.setChgId(regId);		//로그인 ID
		
		resultcnt = custMgtMapper.insertChrgInfo(chrgInfo);
		
		Date now = new Date();
        String presentYm = DateUtils.dateToStr(now, "yyyyMM");  
        ChrgAmtDto chrgAmtDto = new ChrgAmtDto();
        
        if (presentYm.equals(StrYm)) {
		
			if ("E".equals(insertChrgReqDto.getChrgDiv())) {
				//소멸 충전금 업데이트
				chrgAmtDto.setUserSeq(userInfo.getUserSeq());
				chrgAmtDto.setLmtYm(chrgInfo.getStrtYm());
				chrgAmtDto.setExtcChrgAmt(chrgInfo.getChrgAmt());
				chrgAmtDto.setCfwdChrgAmt("0");
				
			}else if ("C".equals(insertChrgReqDto.getChrgDiv())) {
				//이월 충전금 업데이트
				chrgAmtDto.setUserSeq(userInfo.getUserSeq());
				chrgAmtDto.setLmtYm(chrgInfo.getStrtYm());
				chrgAmtDto.setCfwdChrgAmt(chrgInfo.getChrgAmt());
				chrgAmtDto.setExtcChrgAmt("0");
			}
			if(resultcnt > 0) {
				resultcnt =  custMgtMapper.updateChrgAmt(chrgAmtDto);
			}else {
				logger.error("충전금 등록 오류");
			}
	        
	        //update성공시
	        if (resultcnt>0) {
	        	String prefix = getCurrentDate(YEAR_MONTH_DAY);
	        	String webReqId = "";
	        	
        		// 1. webReqId 채번
 	 			webReqId = prefix + custMgtMapper.selectSequence(WEB_REQ_ID);
 	 			BigDecimal chargeAmt= BigDecimal.ZERO;
 	 			BigDecimal zero 	= BigDecimal.ZERO;
 	 			
 	 			//충전 금액 조회
 	 			chargeAmt = new BigDecimal(chrgInfo.getChrgAmt());
 	 			//알림문자 발송테이블 insert
 	 			WebMsgCliDto ezMsgDto = new WebMsgCliDto();
 	 			ezMsgDto.setTableName("EZ_MSG_REAL");
 	 			ezMsgDto.setTrafficType("real");
 	 			String clientKey = generateClientKey("R", 10);
 	 			ezMsgDto.setClientKey(clientKey);
 	 			ezMsgDto.setReqProduct("LMS");
 	 			ezMsgDto.setMsgStatus("ready");
 	 			ezMsgDto.setCallbackNumber("15445992");
 	 			ezMsgDto.setPhone(userInfo.getHpNo());
 	 			ezMsgDto.setWebReqId(webReqId);
 	 			ezMsgDto.setOrderId("2");
 	 			
 	 			String msg = "[LG U+메시지허브이지]\n이번 달 이벤트 충전 금액이 충전 되었습니다.\n*충전 금액 : "+chargeAmt+"원";
 	 			ezMsgDto.setMsg(msg);
 	 			
 	 			custMgtMapper.insertWebMsgCli(ezMsgDto);
 	 			logger.info("충전 알림 등록 : [{}]", ezMsgDto.toString());
 	 			
 	 			//알림 이력 insert
 	 			NotiHistDto notihist = new NotiHistDto();
 	 			String notiSeq = custMgtMapper.selectNotiSeq();
 	 			notihist.setUserSeq(userInfo.getUserSeq());
 	 			notihist.setNotiSeq(notiSeq);
 	 			notihist.setNotiMsg(msg);
 	 			notihist.setWebReqId(webReqId);
 	 			
 	 			custMgtMapper.insertNotiHst(notihist);
 	 			logger.info("충전 알림 이력 등록 : [{}]", ezMsgDto.toString());
	        }else{
	        	logger.error("충전금 한도 업데이트 오류");
	        }

        }
		return new InsertChrgResDto(ApiResponseCode.SUCCESS);
	}

	/**
	 * date : 2023. 3. 15.
	 * auth : won
	 * desc : 충전관리 수정
	 * @param paramMap
	 * @return 
	 */
	public UpdateChrgResDto UpdateChrg(@Valid UpdateChrgReqDto updateChrgReqDto) {
		
		CustMgtMapper custMgtMapper = sqlSessionMaster.getMapper(CustMgtMapper.class);
		
		// 1. 사용여부 update
		custMgtMapper.updateChrg(updateChrgReqDto);
		
		// 2. 새 정보 insert
        String chrgSeq = custMgtMapper.getChrgSeq();
        SvcUserInfo userInfo = custMgtMapper.selectUserInfo(updateChrgReqDto.getUserId());
        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        UserDetails userDetails = (UserDetails) principal;
        String regId = userDetails.getUsername();
        
        logger.debug("updateChrgReqDto= {}", updateChrgReqDto);
        
		ChrgInfo chrgInfo = new ChrgInfo();
		chrgInfo.setChrgSeq(chrgSeq);
		chrgInfo.setUserSeq(userInfo.getUserSeq());
		chrgInfo.setChrgDiv(updateChrgReqDto.getChrdDiv());
		String StrYm = updateChrgReqDto.getStrtYm().replace("-", "").substring(0, 6);
		chrgInfo.setStrtYm(StrYm);
		String EndYm = updateChrgReqDto.getEndYm().replace("-", "").substring(0, 6);
		chrgInfo.setEndYm(EndYm);
		chrgInfo.setChrgAmt(updateChrgReqDto.getChrgAmt());
		chrgInfo.setRegId(regId);		//로그인 ID
		chrgInfo.setChgId(regId);		//로그인 ID
		
		custMgtMapper.addChrg(chrgInfo);
		
		return new UpdateChrgResDto(ApiResponseCode.SUCCESS);
	}

	/**
	 * date : 2023. 3. 15.
	 * auth : won
	 * desc : 충전관리 삭제
	 * @param paramMap
	 * @return 
	 */
	public DeleteChrgResDto DeleteChrg(@Valid DeleteChrgReqDto deleteChrgReqDto) {
		
		logger.debug("deleteChrgReqDto={}",deleteChrgReqDto);
		CustMgtMapper custMgtMapper = sqlSessionMaster.getMapper(CustMgtMapper.class);
		custMgtMapper.deleteChrg(deleteChrgReqDto);
		return new DeleteChrgResDto(ApiResponseCode.SUCCESS);
	}

	/**
	 * date : 2022. 4. 25.
	 * auth : ckr
	 * desc : 유저ID 목록 조회
	 * @param userListReqDto
	 * @return
	 */
	public UserListResDto userList(UserListReqDto userListReqDto) {
		CustMgtMapper custMgtMapper = sqlSessionMaster.getMapper(CustMgtMapper.class);
		int totalCnt = custMgtMapper.selectuserTotalCnt(userListReqDto);

		if(totalCnt == 0) {
			UserListRes userListRes = new UserListRes();
			userListRes.setList(new ArrayList<>());
			return new UserListResDto(ApiResponseCode.CM_NOT_FOUND, userListRes);
		}

		List<UserinInfo> userinInfo = custMgtMapper.selectUserList(userListReqDto);

		Paging paging = new Paging();
		paging.setTotalCnt(String.valueOf(totalCnt));

		UserListRes userListRes = new UserListRes();
		userListRes.setList(userinInfo);

		return new UserListResDto(ApiResponseCode.SUCCESS, userListRes);
	}

	/**
	 * 날짜 형식을 받아서 오늘 날짜를 해당 형식으로 반환
	 *
	 * @param format
	 * @return
	 */
	public String getCurrentDate(String format) {
		Date date = Calendar.getInstance().getTime();
		DateFormat dateFormat = new SimpleDateFormat(format);
		return dateFormat.format(date);
	}

	/**
	 * clientKey 생성
	 * 
	 * @param rsvtType
	 * @return
	 */
	public String generateClientKey(String lineTpCdKey, int length) {
		String prefix = DateUtil.getCurrentDate("yyyyMMddHHmmss") + lineTpCdKey;
		String clientKey = "";
		
		clientKey = CommonUtils.getCommonId(prefix, length);
		
		return clientKey;
	}
    
	/* 2023-03-07 add request 부분
	 * date : 2023. 1. 1.
	 * auth : won
	 * desc : 요금제 구매 내역 목록 조회
	 * @param UserLmtListReqDto 
	 * @return UserLmtListRestDto
	 * @
	
	public UserLmtListResDto BLNCList(UserLmtListReqDto userLmtListReqDto) {
		 CustMgtMapper custMgtMapper = sqlSessionMaster.getMapper(CustMgtMapper.class);
		 
		 String nowPage = String.valueOf(userLmtListReqDto.getPage());
		 int totalCnt = custMgtMapper.selectUserLmtListTotalCnt(userLmtListReqDto);
		 if (totalCnt==0) {
			UserLmtListRes userLmtListRes = new UserLmtListRes();
			userLmtListRes.setList(new ArrayList<>());
			
			Paging paging = new Paging();
			paging.setPage(nowPage);
			paging.setTotalCnt(String.valueOf(totalCnt));
			userLmtListRes.setPaging(paging);
			
			return new UserLmtListResDto(ApiResponseCode.CM_NOT_FOUND, userLmtListRes);
		}
		 
		 int page = userLmtListReqDto.getPage();
		 int pagePerRows = userLmtListReqDto.getPagePerRows();
		 page = (page-1) * pagePerRows;
		 userLmtListReqDto.setPage(page);
		 
		 //리스트 조회
		 List<UserLmtList> userlmtlist = custMgtMapper.selectBLNCLists(userLmtListReqDto);
		 
		 UserLmtListRes userLmtListRes = new UserLmtListRes();
		 userLmtListRes.setList(userlmtlist);
		 
		 Paging paging = new Paging();
		 paging.setPage(nowPage);
		 paging.setTotalCnt(String.valueOf(totalCnt));
		 userLmtListRes.setPaging(paging);
		 
		 return new UserLmtListResDto(ApiResponseCode.SUCCESS, userLmtListRes);
	}

	*
	 * date : 2023. 1. 1.
	 * auth : won
	 * desc : 요금제 구매 내역 정보 목록 엑셀 다운로드
	 *
	 * @param userLmtListExcelReqDto
	 * @return UserLmtListExcelResDto
	 
	public UserLmtListExcelResDto userLmtListExcel(@Valid UserLmtListExcelReqDto userLmtListExcelReqDto) {
		
		 CustMgtMapper custMgtMapper = sqlSessionMaster.getMapper(CustMgtMapper.class);
		
		UserLmtListRes userLmtListRes = new UserLmtListRes();
		//리스트 조회
		List<UserLmtList> userLmtLists = custMgtMapper.selectBLNCListsExcel(userLmtListExcelReqDto);
		
		 Paging paging = new Paging();
		 paging.setTotalCnt(String.valueOf(userLmtLists.size()));
		 userLmtListRes.setPaging(paging);
		 userLmtListRes.setList(userLmtLists);
		 
		return new UserLmtListExcelResDto(ApiResponseCode.SUCCESS,userLmtListRes);
	}
 */

}
