package com.oqpo.api.service.loanmng;


import com.kicc.EasyPayClient;
import com.oqpo.api.entity.loanmng.LoanMgntBaseInfoEntity;
import com.oqpo.api.entity.loanmng.LoanMgntDsptProcEntity;
import com.oqpo.api.entity.loanmng.LoanMgntDtlHstEntity;
import com.oqpo.api.entity.oper.UserMngEntity;
import com.oqpo.api.entity.settmng.PgKiccBaseInfoEntity;
import com.oqpo.api.entity.settmng.PgKiccPayPtclEntity;
import com.oqpo.api.entity.settmng.StlMgntBaseInfoEntity;
import com.oqpo.api.entity.stinfo.BrandEntity;
import com.oqpo.api.enums.*;
import com.oqpo.api.exception.GlobalException;
import com.oqpo.api.mapper.loanmng.DsptMngMapper;
import com.oqpo.api.mapper.loanmng.UnpaidMngMapper;
import com.oqpo.api.mapper.oper.UserMngMapper;
import com.oqpo.api.mapper.stinfo.BrandMapper;
import com.oqpo.api.service.CommonService;
import com.oqpo.api.util.DateUtil;
import com.oqpo.api.util.StringUtil;
import com.oqpo.api.web.dto.request.loanmng.EasypayPaymentCreateRequest;
import com.oqpo.api.web.dto.request.loanmng.EasypayPaymentReqData;
import com.oqpo.api.web.dto.request.loanmng.EasypayPaymentRequest;
import com.oqpo.api.web.dto.response.loanmng.EasypayPaymentCreateResponse;
import com.oqpo.api.web.dto.response.loanmng.EasypayPaymentResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Service
@Slf4j
public class EasypayPaymentService extends CommonService {

    @Autowired
    private UnpaidMngMapper unpaidMngMapper;

    @Autowired
    private UserMngMapper userMngMapper;

    @Autowired
    private BrandMapper brandMapper;

    @Autowired
    private DsptMngMapper dsptMngMapper;

    @Value("${kicc.gateway}")
    private String kiccGatewayUrl;
    @Value("${kicc.cert_dir}")
    private String kiccCertFile;
    @Value("${kicc.log_dir}")
    private String kiccLogDir;
    @Value("${kicc.javascript_url}")
    private String kiccJavaScriptUrl;
    @Value("${kicc.action.web_url}")
    private String kiccActionWebUrl;
    @Value("${kicc.action.mobile_url}")
    private String kiccActionMobileUrl;

    /* 결제 생성 */
    @Transactional
    public EasypayPaymentCreateResponse createPayment(String userId, EasypayPaymentCreateRequest easypayPaymentCreateRequest) throws Exception {
        EasypayPaymentCreateResponse response = new EasypayPaymentCreateResponse();

        // 1. 주문번호 생성
        response.setPoOrdNo(fnGetDealNo(36, ""));

        // 2. PG 관련 정보
        PgKiccBaseInfoEntity pgInfo = unpaidMngMapper.selectPgKiccBaseInfo(easypayPaymentCreateRequest.getBrandId());
        response.setMallId(pgInfo.getMallId());

        // 3. 사용자정보 조회 및 매핑
        UserMngEntity userInfo = userMngMapper.selectUserInfo(userId);
        response.setOrdNm(userInfo.getUserNm()); // 구매자명
        response.setGoodsNm(easypayPaymentCreateRequest.getStoreId() //
                + "-" + DateUtil.getCurrentDateFormat("MMdd") //
                + "-" + String.format("%d", easypayPaymentCreateRequest.getGoodsAmt() / 1000));
        response.setOrdTel(StringUtil.isEmpty(userInfo.getTelNo()) && userInfo.getTelNo().startsWith("010") ? userInfo.getTelNo() : null); // 휴대전화번호
        response.setOrdEmail(userInfo.getEmail()); // 이메일

        // 4. 이지페이 결제 URL 매핑
        response.setKicc_javascript_url(kiccJavaScriptUrl);
        response.setKicc_action_web_url(kiccActionWebUrl);
        response.setKicc_action_mobile_url(kiccActionMobileUrl);
        return response;
    }

    /* 결제 요청 */
    @Transactional
    public EasypayPaymentResponse requestPayment(String userId, HttpServletRequest request, EasypayPaymentRequest easypayPaymentRequest) throws Exception {
        try {
            log.info("[REQUEST_PAYMENT] REQ : " + easypayPaymentRequest.toString());

            // TODO 결제금액과 미납금 비교

            /* -------------------------------------------------------------------------- */
            /* ::: 처리구분 설정                                                          */
            /* -------------------------------------------------------------------------- */
            final String TRAN_CD_NOR_PAYMENT = "00101000"; // 승인(일반, 에스크로)
            final String TRAN_CD_NOR_MGR = "00201000"; // 변경(일반, 에스크로)
            @SuppressWarnings("unused") final String TRAN_CD_NOR_MALL = "00201030"; // 셀러(다중정산)

            /* -------------------------------------------------------------------------- */
            /* ::: 지불정보 설정                                                          */
            /* -------------------------------------------------------------------------- */
            final String GW_URL = (String) kiccGatewayUrl; // GatewayURL
            final String GW_PORT = "80"; // 포트번호(변경불가)

            /* -------------------------------------------------------------------------- */
            /* ::: 지불 데이터 셋업 (업체에 맞게 수정)                                    */
            /* -------------------------------------------------------------------------- */
            /* ※ 주의 ※                                                                 */
            /* cert_file 변수 설정                                                        */
            /* - pg_cert.pem 파일이 있는 디렉토리의  절대 경로 설정                       */
            /* log_dir 변수 설정                                                          */
            /* - log 디렉토리 설정                                                        */
            /* log_level 변수 설정                                                        */
            /* - log 레벨 설정 (1 to 99(높을수록 상세))                                   */
            /* -------------------------------------------------------------------------- */
            final String CERT_FILE = (String) kiccCertFile;
            final String LOG_DIR = (String) kiccLogDir;
            final int LOG_LEVEL = 1;

            /* -------------------------------------------------------------------------- */
            /* ::: 승인요청 정보 설정                                                     */
            /* -------------------------------------------------------------------------- */
            // [헤더]
            String tr_cd = ""; // [필수]결제창요청구분
            String trace_no = ""; // [필수]추적번호
            String order_no = ""; // [필수]가맹점주문번호
            String mall_id = ""; // [필수]가맹점ID
            // [공통]
            String encrypt_data = ""; // [필수]암호화전문
            String sessionkey = ""; // [필수]세션키

            if (!StringUtil.isEmpty(easypayPaymentRequest.getSp_tr_cd())) {
                // [헤더]
                tr_cd = StringUtil.null2str(easypayPaymentRequest.getSp_tr_cd()); // [필수]결제창요청구분
                trace_no = StringUtil.null2str(easypayPaymentRequest.getSp_trace_no()); // [필수]추적번호
                order_no = StringUtil.null2str(easypayPaymentRequest.getSp_order_no()); // [필수]가맹점주문번호
                mall_id = StringUtil.null2str(easypayPaymentRequest.getSp_mall_id()); // [필수]가맹점ID
                // [공통]
                encrypt_data = StringUtil.null2str(easypayPaymentRequest.getSp_encrypt_data()); // [필수]암호화전문
                sessionkey = StringUtil.null2str(easypayPaymentRequest.getSp_sessionkey()); // [필수]세션키
            } else {
                // [헤더]
                tr_cd = StringUtil.null2str(easypayPaymentRequest.getEP_tr_cd()); // [필수]결제창요청구분
                trace_no = StringUtil.null2str(easypayPaymentRequest.getEP_trace_no()); // [필수]추적번호
                order_no = StringUtil.null2str(easypayPaymentRequest.getEP_order_no()); // [필수]가맹점주문번호
                mall_id = StringUtil.null2str(easypayPaymentRequest.getEP_mall_id()); // [필수]가맹점ID
                // [공통]
                encrypt_data = StringUtil.null2str(easypayPaymentRequest.getEP_encrypt_data()); // [필수]암호화전문
                sessionkey = StringUtil.null2str(easypayPaymentRequest.getEP_sessionkey()); // [필수]세션키
            }

            /* -------------------------------------------------------------------------- */
            /* ::: 변경관리 정보 설정                                                     */
            /* -------------------------------------------------------------------------- */
            String mgr_txtype = StringUtil.null2str(easypayPaymentRequest.getMgr_txtype()); // [필수]거래구분
            String mgr_subtype = StringUtil.null2str(easypayPaymentRequest.getMgr_subtype()); // [선택]변경세부구분
            String org_cno = StringUtil.null2str(easypayPaymentRequest.getOrg_cno()); // [필수]원거래고유번호
            String mgr_amt = StringUtil.null2str(easypayPaymentRequest.getMgr_amt()); // [선택]금액
            String mgr_rem_amt = StringUtil.null2str(easypayPaymentRequest.getMgr_rem_amt()); // [선택]부분취소잔액
            String mgr_bank_cd = StringUtil.null2str(easypayPaymentRequest.getMgr_bank_cd()); // [선택]환불계좌은행코드
            String mgr_account = StringUtil.null2str(easypayPaymentRequest.getMgr_account()); // [선택]환불계좌번호
            String mgr_depositor = StringUtil.null2str(easypayPaymentRequest.getMgr_depositor()); // [선택]환불계좌예금주명

            /* -------------------------------------------------------------------------- */
            /* ::: 전문                                                                   */
            /* -------------------------------------------------------------------------- */
            // String mgr_data    = "";     // 변경정보
            // String mall_data   = "";     // 요청전문

            /* -------------------------------------------------------------------------- */
            /* ::: 결제 결과                                                              */
            /* -------------------------------------------------------------------------- */
            String bDBProc = "";     //가맹점DB처리성공여부
            String res_cd = "";     //응답코드
            String res_msg = "";     //응답메시지
            String r_cno = "";     //PG거래번호
            String r_amount = "";     //총 결제금액
            String r_order_no = "";     //주문번호
            String r_auth_no = "";     //승인번호
            String r_tran_date = "";     //승인일시
            String r_escrow_yn = "";     //에스크로 사용유무
            String r_complex_yn = "";     //복합결제 유무
            String r_stat_cd = "";     //상태코드
            String r_stat_msg = "";     //상태메시지
            String r_pay_type = "";     //결제수단
            String r_mall_id = "";     //가맹점 Mall ID
            String r_card_no = "";     //카드번호
            String r_issuer_cd = "";     //발급사코드
            String r_issuer_nm = "";     //발급사명
            String r_acquirer_cd = "";     //매입사코드
            String r_acquirer_nm = "";     //매입사명
            String r_install_period = "";     //할부개월
            String r_noint = "";     //무이자여부
            String r_part_cancel_yn = "";     //부분취소 가능여부
            String r_card_gubun = "";     //신용카드 종류
            String r_card_biz_gubun = "";     //신용카드 구분
            String r_cpon_flag = "";     //쿠폰사용유무
            String r_bank_cd = "";     //은행코드
            String r_bank_nm = "";     //은행명
            String r_account_no = "";     //계좌번호
            String r_deposit_nm = "";     //입금자명
            String r_expire_date = "";     //계좌사용만료일
            String r_cash_res_cd = "";     //현금영수증 결과코드
            String r_cash_res_msg = "";     //현금영수증 결과메세지
            String r_cash_auth_no = "";     //현금영수증 승인번호
            String r_cash_tran_date = "";     //현금영수증 승인일시
            String r_cash_issue_type = "";     //현금영수증발행용도
            String r_cash_auth_type = "";     //인증구분
            String r_cash_auth_value = "";     //인증번호
            String r_auth_id = "";     //PhoneID
            String r_billid = "";     //인증번호
            String r_mobile_no = "";     //휴대폰번호
            String r_mob_ansim_yn = "";     //안심결제 사용유무
            String r_ars_no = "";     //전화번호
            String r_cp_cd = "";     //포인트사/쿠폰사
            String r_cpon_auth_no = "";     //쿠폰승인번호
            String r_cpon_tran_date = "";     //쿠폰승인일시
            String r_cpon_no = "";     //쿠폰번호
            String r_remain_cpon = "";     //쿠폰잔액
            String r_used_cpon = "";     //쿠폰 사용금액
            String r_rem_amt = "";     //잔액
            String r_bk_pay_yn = "";     //장바구니 결제여부
            String r_canc_acq_date = "";     //매입취소일시
            String r_canc_date = "";     //취소일시
            String r_refund_date = "";     //환불예정일시

            /* -------------------------------------------------------------------------- */
            /* ::: EasyPayClient 인스턴스 생성 [변경불가 !!].                             */
            /* -------------------------------------------------------------------------- */
            EasyPayClient easyPayClient = new EasyPayClient();
            easyPayClient.easypay_setenv_init(GW_URL, GW_PORT, CERT_FILE, LOG_DIR, LOG_LEVEL);
            easyPayClient.easypay_reqdata_init();

            /* -------------------------------------------------------------------------- */
            /* ::: 승인요청(플러그인 암호화 전문 설정)                                    */
            /* -------------------------------------------------------------------------- */
            if (TRAN_CD_NOR_PAYMENT.equals(tr_cd)) {

                // 승인요청 전문 설정
                easyPayClient.easypay_set_trace_no(trace_no);
                easyPayClient.easypay_encdata_set(encrypt_data, sessionkey);
            }
            /* -------------------------------------------------------------------------- */
            /* ::: 변경관리 요청                                                          */
            /* -------------------------------------------------------------------------- */
            else if (TRAN_CD_NOR_MGR.equals(tr_cd)) {

                int easypay_mgr_data_item;
                easypay_mgr_data_item = easyPayClient.easypay_item("mgr_data");

                easyPayClient.easypay_deli_us(easypay_mgr_data_item, "mgr_txtype", mgr_txtype);          // [필수]거래구분
                easyPayClient.easypay_deli_us(easypay_mgr_data_item, "mgr_subtype", mgr_subtype);          // [선택]변경세부구분
                easyPayClient.easypay_deli_us(easypay_mgr_data_item, "org_cno", org_cno);          // [필수]원거래고유번호
                easyPayClient.easypay_deli_us(easypay_mgr_data_item, "mgr_amt", mgr_amt);          // [선택]금액
                easyPayClient.easypay_deli_us(easypay_mgr_data_item, "mgr_rem_amt", mgr_rem_amt);          // [선택]부분취소 잔액
                easyPayClient.easypay_deli_us(easypay_mgr_data_item, "mgr_bank_cd", mgr_bank_cd);          // [선택]환불계좌 은행코드
                easyPayClient.easypay_deli_us(easypay_mgr_data_item, "mgr_account", mgr_account);          // [선택]환불계좌 번호
                easyPayClient.easypay_deli_us(easypay_mgr_data_item, "mgr_depositor", mgr_depositor);          // [선택]환불계좌 예금주명
                easyPayClient.easypay_deli_us(easypay_mgr_data_item, "req_ip", request.getRemoteAddr());// [필수]요청자 IP
            }
            /* -------------------------------------------------------------------------- */
            /* ::: 실행                                                                   */
            /* -------------------------------------------------------------------------- */
            if (tr_cd.length() > 0) {
                easyPayClient.easypay_run(mall_id, tr_cd, order_no);

                res_cd = easyPayClient.res_cd;
                res_msg = easyPayClient.res_msg;
            } else {
                res_cd = "M114";
                res_msg = "연동 오류|tr_cd값이 설정되지 않았습니다.";
            }

            /* -------------------------------------------------------------------------- */
            /* ::: 결과 처리                                                              */
            /* -------------------------------------------------------------------------- */

            r_cno = easyPayClient.easypay_get_res("cno");     //PG거래번호
            r_amount = easyPayClient.easypay_get_res("amount");     //총 결제금액
            r_order_no = easyPayClient.easypay_get_res("order_no");     //주문번호
            r_auth_no = easyPayClient.easypay_get_res("auth_no");     //승인번호
            r_tran_date = easyPayClient.easypay_get_res("tran_date");     //승인일시
            r_escrow_yn = easyPayClient.easypay_get_res("escrow_yn");     //에스크로 사용유무
            r_complex_yn = easyPayClient.easypay_get_res("complex_yn");     //복합결제 유무
            r_stat_cd = easyPayClient.easypay_get_res("stat_cd");     //상태코드
            r_stat_msg = easyPayClient.easypay_get_res("stat_msg");     //상태메시지
            r_pay_type = easyPayClient.easypay_get_res("pay_type");     //결제수단
            r_mall_id = easyPayClient.easypay_get_res("mall_id");     //가맹점 Mall ID
            r_card_no = easyPayClient.easypay_get_res("card_no");     //카드번호
            r_issuer_cd = easyPayClient.easypay_get_res("issuer_cd");     //발급사코드
            r_issuer_nm = easyPayClient.easypay_get_res("issuer_nm");     //발급사명
            r_acquirer_cd = easyPayClient.easypay_get_res("acquirer_cd");     //매입사코드
            r_acquirer_nm = easyPayClient.easypay_get_res("acquirer_nm");     //매입사명
            r_install_period = easyPayClient.easypay_get_res("install_period");     //할부개월
            r_noint = easyPayClient.easypay_get_res("noint");     //무이자여부
            r_part_cancel_yn = easyPayClient.easypay_get_res("part_cancel_yn");     //부분취소 가능여부
            r_card_gubun = easyPayClient.easypay_get_res("card_gubun");     //신용카드 종류
            r_card_biz_gubun = easyPayClient.easypay_get_res("card_biz_gubun");     //신용카드 구분
            r_cpon_flag = easyPayClient.easypay_get_res("cpon_flag");     //쿠폰사용유무
            r_bank_cd = easyPayClient.easypay_get_res("bank_cd");     //은행코드
            r_bank_nm = easyPayClient.easypay_get_res("bank_nm");     //은행명
            r_account_no = easyPayClient.easypay_get_res("account_no");     //계좌번호
            r_deposit_nm = easyPayClient.easypay_get_res("deposit_nm");     //입금자명
            r_expire_date = easyPayClient.easypay_get_res("expire_date");     //계좌사용만료일
            r_cash_res_cd = easyPayClient.easypay_get_res("cash_res_cd");     //현금영수증 결과코드
            r_cash_res_msg = easyPayClient.easypay_get_res("cash_res_msg");     //현금영수증 결과메세지
            r_cash_auth_no = easyPayClient.easypay_get_res("cash_auth_no");     //현금영수증 승인번호
            r_cash_tran_date = easyPayClient.easypay_get_res("cash_tran_date");     //현금영수증 승인일시
            r_cash_issue_type = easyPayClient.easypay_get_res("cash_issue_type");     //현금영수증발행용도
            r_cash_auth_type = easyPayClient.easypay_get_res("cash_auth_type");     //인증구분
            r_cash_auth_value = easyPayClient.easypay_get_res("cash_auth_value");     //인증번호
            r_auth_id = easyPayClient.easypay_get_res("auth_id");     //PhoneID
            r_billid = easyPayClient.easypay_get_res("billid");     //인증번호
            r_mobile_no = easyPayClient.easypay_get_res("mobile_no");     //휴대폰번호
            r_mob_ansim_yn = easyPayClient.easypay_get_res("mob_ansim_yn");     //안심결제 사용유무
            r_ars_no = easyPayClient.easypay_get_res("ars_no");     //전화번호
            r_cp_cd = easyPayClient.easypay_get_res("cp_cd");     //포인트사/쿠폰사
            r_cpon_auth_no = easyPayClient.easypay_get_res("cpon_auth_no");     //쿠폰승인번호
            r_cpon_tran_date = easyPayClient.easypay_get_res("cpon_tran_date");     //쿠폰승인일시
            r_cpon_no = easyPayClient.easypay_get_res("cpon_no");     //쿠폰번호
            r_remain_cpon = easyPayClient.easypay_get_res("remain_cpon");     //쿠폰잔액
            r_used_cpon = easyPayClient.easypay_get_res("used_cpon");     //쿠폰 사용금액
            r_rem_amt = easyPayClient.easypay_get_res("rem_amt");     //잔액
            r_bk_pay_yn = easyPayClient.easypay_get_res("bk_pay_yn");     //장바구니 결제여부
            r_canc_acq_date = easyPayClient.easypay_get_res("canc_acq_date");     //매입취소일시
            r_canc_date = easyPayClient.easypay_get_res("canc_date");     //취소일시
            r_refund_date = easyPayClient.easypay_get_res("refund_date");     //환불예정일시

            /* -------------------------------------------------------------------------- */
            /* ::: 가맹점 DB 처리                                                         */
            /* -------------------------------------------------------------------------- */
            /* 응답코드(res_cd)가 "0000" 이면 정상승인 입니다.                            */
            /* r_amount가 주문DB의 금액과 다를 시 반드시 취소 요청을 하시기 바랍니다.     */
            /* DB 처리 실패 시 취소 처리를 해주시기 바랍니다.                             */
            /* -------------------------------------------------------------------------- */
            log.info("[REQUEST_PAYMENT] res_cd : " + res_cd);
            EasypayPaymentResponse easyResult = new EasypayPaymentResponse();
            easyResult.setRes_cd(res_cd);
            easyResult.setRes_msg(res_msg);
            easyResult.setCno(r_cno);
            easyResult.setAmount(r_amount);
            easyResult.setOrder_no(r_order_no);
            easyResult.setAuth_no(r_auth_no);
            easyResult.setTran_date(r_tran_date);
            easyResult.setEscrow_yn(r_escrow_yn);
            easyResult.setComplex_yn(r_complex_yn);
            easyResult.setStat_cd(r_stat_cd);
            easyResult.setStat_msg(r_stat_msg);
            easyResult.setPay_type(r_pay_type);
            easyResult.setMall_id(r_mall_id);
            easyResult.setCard_no(r_card_no);
            easyResult.setIssuer_cd(r_issuer_cd);
            easyResult.setIssuer_nm(r_issuer_nm);
            easyResult.setAcquirer_cd(r_acquirer_cd);
            easyResult.setAcquirer_nm(r_acquirer_nm);
            easyResult.setInstall_period(r_install_period);
            easyResult.setNoint(r_noint);
            easyResult.setPart_cancel_yn(r_part_cancel_yn);
            easyResult.setCard_gubun(r_card_gubun);
            easyResult.setCard_biz_gubun(r_card_biz_gubun);
            easyResult.setCpon_flag(r_cpon_flag);
            easyResult.setBank_cd(r_bank_cd);
            easyResult.setBank_nm(r_bank_nm);
            easyResult.setAccount_no(r_account_no);
            easyResult.setDeposit_nm(r_deposit_nm);
            easyResult.setExpire_date(r_expire_date);
            easyResult.setCash_res_cd(r_cash_res_cd);
            easyResult.setCash_res_msg(r_cash_res_msg);
            easyResult.setCash_auth_no(r_cash_auth_no);
            easyResult.setCash_tran_date(r_cash_tran_date);
            easyResult.setCash_issue_type(r_cash_issue_type);
            easyResult.setCash_auth_type(r_cash_auth_type);
            easyResult.setCash_auth_value(r_cash_auth_value);
            easyResult.setAuth_id(r_auth_id);
            easyResult.setBillid(r_billid);
            easyResult.setMobile_no(r_mobile_no);
            easyResult.setMob_ansim_yn(r_mob_ansim_yn);
            easyResult.setArs_no(r_ars_no);
            easyResult.setCp_cd(r_cp_cd);
            easyResult.setCpon_auth_no(r_cpon_auth_no);
            easyResult.setCpon_tran_date(r_cpon_tran_date);
            easyResult.setCpon_no(r_cpon_no);
            easyResult.setRemain_cpon(r_remain_cpon);
            easyResult.setUsed_cpon(r_used_cpon);
            easyResult.setRem_amt(r_rem_amt);
            easyResult.setBk_pay_yn(r_bk_pay_yn);
            easyResult.setCanc_acq_date(r_canc_acq_date);
            easyResult.setCanc_date(r_canc_date);
            easyResult.setRefund_date(r_refund_date);

            if (res_cd.equals("0000")) {
                bDBProc = "true"; // DB처리 성공 시 "true", 실패 시 "false"
                try {
                    // TODO 결과에 대해 처리한다.
                    // 1. KICCPG거래내역 등록
                    PgKiccPayPtclEntity payInfo = new PgKiccPayPtclEntity();
                    payInfo.setPoOrdNo(easypayPaymentRequest.getPoOrdNo());
                    payInfo.setBrandId(easypayPaymentRequest.getBrandId());
                    payInfo.setStoreId(easypayPaymentRequest.getStoreId());
                    payInfo.setMallId(mall_id);
                    // payInfo.setPaymentNo(null); // TODO 결제번호
                    payInfo.setTranType("O"); // 거래타입(O:주문,C:취소)
                    payInfo.setResCd(res_cd);
                    payInfo.setResMsg(res_msg);
                    payInfo.setCno(r_cno);
                    payInfo.setAmount(r_amount);
                    payInfo.setAuthNo(r_auth_no);
                    payInfo.setTranDate(r_tran_date);
                    payInfo.setStatCd(r_stat_cd);
                    payInfo.setStatMsg(r_stat_msg);
                    payInfo.setPayType(r_pay_type);
                    payInfo.setCardNo(r_card_no);
                    payInfo.setIssuerCd(r_issuer_cd);
                    payInfo.setIssuerNm(r_issuer_nm);
                    payInfo.setAcquirerCd(r_acquirer_cd);
                    payInfo.setAcquirerNm(r_acquirer_nm);
                    payInfo.setInstallPeriod(r_install_period);
                    payInfo.setNoint(r_noint);
                    // payInfo.setCancelYn(null);
                    // payInfo.setCancelDate(null);
                    unpaidMngMapper.insertPgKiccPayPtcl(userId, payInfo);

                    if (PayTpCd.AFTER_PAYMENT.getCd().equals(easypayPaymentRequest.getPayTpCd())) { // 후불(결제)
                        procAfterPayment(userId, r_amount, r_pay_type, payInfo, easypayPaymentRequest);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    bDBProc = "false";
                }

                if (bDBProc.equals("false")) {
                    // 승인요청이 실패 시 아래 실행
                    if (TRAN_CD_NOR_PAYMENT.equals(tr_cd)) {
                        int easypay_mgr_data_item;

                        easyPayClient.easypay_reqdata_init();

                        tr_cd = TRAN_CD_NOR_MGR;
                        easypay_mgr_data_item = easyPayClient.easypay_item("mgr_data");
                        if (!r_escrow_yn.equals("Y")) {
                            easyPayClient.easypay_deli_us(easypay_mgr_data_item, "mgr_txtype", "40");
                        } else {
                            easyPayClient.easypay_deli_us(easypay_mgr_data_item, "mgr_txtype", "61");
                            easyPayClient.easypay_deli_us(easypay_mgr_data_item, "mgr_subtype", "ES02");
                        }
                        easyPayClient.easypay_deli_us(easypay_mgr_data_item, "org_cno", r_cno);
                        easyPayClient.easypay_deli_us(easypay_mgr_data_item, "order_no", order_no);
                        easyPayClient.easypay_deli_us(easypay_mgr_data_item, "req_ip", request.getRemoteAddr());
                        easyPayClient.easypay_deli_us(easypay_mgr_data_item, "req_id", "MALL_R_TRANS");
                        easyPayClient.easypay_deli_us(easypay_mgr_data_item, "mgr_msg", "DB 처리 실패로 망취소");

                        easyPayClient.easypay_run(mall_id, tr_cd, order_no);

                        res_cd = easyPayClient.res_cd;
                        res_msg = easyPayClient.res_msg;
                        r_cno = easyPayClient.easypay_get_res("cno"); // PG거래번호
                        r_canc_date = easyPayClient.easypay_get_res("canc_date"); // 취소일시
                    }
                }
            }
            return easyResult;
        } catch (GlobalException e) {
            e.getStackTrace();
            throw new GlobalException(e.getSystemMessageCode());
        } catch (Exception e) {
            e.getStackTrace();
            throw new RuntimeException();
        }
    }

    private void procAfterPayment(String userId, String r_amount, String r_pay_type, PgKiccPayPtclEntity payInfo, EasypayPaymentRequest easypayPaymentRequest) throws Exception {
        // 2. 여신관리기본정보
        LoanMgntBaseInfoEntity infoEntity = dsptMngMapper.selectLoanMgntBaseInfo(payInfo.getBrandId(), payInfo.getStoreId());

        long trscBfBal = infoEntity.getAcctBal();
        long trscAfBal = infoEntity.getAcctBal() + Long.parseLong(r_amount);
        // 사용금액합계 감소
        infoEntity.setUseAmtTotal(infoEntity.getUseAmtTotal() - Long.parseLong(r_amount));
        unpaidMngMapper.updateLoanMgntBaseInfo4UnpaidPay(userId, infoEntity);

        // 3. 여신관리상세이력
        // 3.1 입금 처리
        LoanMgntDtlHstEntity hstEntity1 = new LoanMgntDtlHstEntity();
        hstEntity1.setLoanMgntUnqNo(infoEntity.getLoanMgntUnqNo());
        hstEntity1.setLoanRegDt(DateUtil.getCurrentDate());
        hstEntity1.setLoanRegTm(DateUtil.getCurrentTime());
        hstEntity1.setDpstPayDvsn(DpstPayDvsn.DEPOSIT.getCd());
        // 11:신용카드, 21:계좌이체
        if ("11".equals(r_pay_type)) {
            hstEntity1.setMediaDvsn(MediaDvsn.CARD.getCd());
        } else if ("21".equals(r_pay_type)) {
            hstEntity1.setMediaDvsn(MediaDvsn.ACCOUNT.getCd());
        }
        hstEntity1.setPayType(PayType.STTL_PAYMENT.getCd());
        hstEntity1.setTrscAmt(Long.parseLong(r_amount)); // 거래금액
        hstEntity1.setTrscBfBal(trscBfBal);
        hstEntity1.setTrscAfBal(trscAfBal);
        dsptMngMapper.insertLoanMgntDtlHst(userId, hstEntity1);

        // 3.2 지급 처리
        LoanMgntDtlHstEntity hstEntity2 = new LoanMgntDtlHstEntity();
        hstEntity2.setLoanMgntUnqNo(infoEntity.getLoanMgntUnqNo());
        hstEntity2.setLoanRegDt(hstEntity1.getLoanRegDt());
        hstEntity2.setLoanRegTm(String.format("%06d", (Integer.parseInt(hstEntity1.getLoanRegTm()) + 1)));
        hstEntity2.setDpstPayDvsn(DpstPayDvsn.PAYMENT.getCd());
        hstEntity2.setMediaDvsn(MediaDvsn.SETTLMENT.getCd());
        hstEntity2.setPayType(PayType.STTL_PAY.getCd());
        hstEntity2.setTrscAmt(Long.parseLong(r_amount)); // 거래금액
        hstEntity2.setTrscBfBal(trscAfBal);
        hstEntity2.setTrscAfBal(trscBfBal);
        dsptMngMapper.insertLoanMgntDtlHst(userId, hstEntity2);

        // 4. 여신관리입금처리
        LoanMgntDsptProcEntity entity = new LoanMgntDsptProcEntity();
        entity.setDsptMgntNo(fnGetDealNo(21, "")); // 입금관리번호
        entity.setReqDt(DateUtil.getCurrentDate());
        entity.setReqTm(DateUtil.getCurrentTime());
        entity.setDpstAmt(Long.parseLong(r_amount)); // 입금금액
        entity.setDpstDt(entity.getReqDt()); // 입금일자
        // entity.setDpstNm(reqDsptRequest.getDpstNm());
        // entity.setRcvAcctNo(reqDsptRequest.getRcvAcctNo());
        // entity.setDpstBnkCd(reqDsptRequest.getDpstBnkCd());
        entity.setDpstStCd(DpstStCd.DPST_APPROVE.getCd());
        entity.setDpstReqId(userId);
        // entity.setDpstReqNm(user.getUserNm());
        entity.setStoreId(payInfo.getStoreId());
        entity.setBrandId(payInfo.getBrandId());
        entity.setPoOrdNo(payInfo.getPoOrdNo());
        entity.setPgId("KICC");
        dsptMngMapper.insertLoanMgntDsptProcInfo(userId, entity);

        // 5. 정산관리기본정보 업데이트
        // easypayPaymentRequest.setR_amount(Long.parseLong(r_amount));
        List<EasypayPaymentReqData> reqDataList = easypayPaymentRequest.getReqDataList();
        for (EasypayPaymentReqData reqData : reqDataList) {
            StlMgntBaseInfoEntity stlEntity = new StlMgntBaseInfoEntity();
            stlEntity.setSttlMgntUnqNo(reqData.getSttlMgntUnqNo()); // 정산관리고유번호
            unpaidMngMapper.updateStlMgntBaseInfo4Rcpt(userId, stlEntity);
        }
    }

}
