package com.madeu.service.web.webpayment.impl;

import com.madeu.constants.Constants;
import com.madeu.dao.web.webauthmenurelation.WebAuthMenuRelationSqlMapDAO;
import com.madeu.dao.web.webdevice.WebDeviceSqlMapDAO;
import com.madeu.dao.web.webkakao.WebKakaoSqlMapDAO;
import com.madeu.dao.web.webkakaotemplate.WebKakaoTemplateSqlMapDAO;
import com.madeu.dao.web.webmember.WebMemberSqlMapDAO;
import com.madeu.dao.web.webmembership.WebMembershipSqlMapDAO;
import com.madeu.dao.web.webpayment.WebPaymentSqlMapDAO;
import com.madeu.dao.web.webpush.WebPushSqlMapDAO;
import com.madeu.dao.web.webreserve.WebReserveSqlMapDAO;
import com.madeu.dao.web.webstockhistory.WebStockHistorySqlMapDAO;
import com.madeu.dao.web.webstocksum.WebStockSumSqlMapDAO;
import com.madeu.dao.web.webtreatmentprocedureproduct.WebTreatmentProcedureProductSqlMapDAO;
import com.madeu.dao.web.webuser.WebUserSqlMapDAO;
import com.madeu.service.common.autokakao.AutoKakaoService;
import com.madeu.service.common.autopush.AutoPushService;
import com.madeu.service.web.webpayment.WebPaymentService;
import com.madeu.util.ValidationCheckUtil;
import lombok.extern.slf4j.Slf4j;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.*;

@Slf4j
@Service("WebPaymentService")
public class WebPaymentServiceImpl implements WebPaymentService {
    @Autowired
    private WebPaymentSqlMapDAO webPaymentSqlMapDAO;
    @Autowired
    private WebMemberSqlMapDAO webMemberSqlMapDAO;
    @Autowired
    private WebReserveSqlMapDAO webReserveSqlMapDAO;
    @Autowired
    private WebMembershipSqlMapDAO webMembershipSqlMapDAO;
    @Autowired
    private WebAuthMenuRelationSqlMapDAO webAuthMenuRelationSqlMapDAO;
    @Autowired
    private WebTreatmentProcedureProductSqlMapDAO webTreatmentProcedureProductSqlMapDAO;
    @Autowired
    private WebStockSumSqlMapDAO webStockSumSqlMapDAO;
    @Autowired
    private WebStockHistorySqlMapDAO webStockHistorySqlMapDAO;

    @Autowired
    private WebUserSqlMapDAO webUserSqlMapDAO;

	@Autowired
	private WebKakaoSqlMapDAO webKakaoSqlMapDAO;

	@Autowired
	private WebKakaoTemplateSqlMapDAO webKakaoTemplateSqlMapDAO;

	@Autowired
	private WebDeviceSqlMapDAO webDeviceSqlMapDAO;

	@Autowired
	private WebPushSqlMapDAO webPushSqlMapDAO;

	@Autowired
	private AutoPushService autoPushService;

	@Autowired
	private AutoKakaoService autoKakaoService;

	@Value("${popbill.sender-phone-num}")
	String senderPhoneNumber;

    /**
     * 수납 리스트 화면으로 이동.
     *
     *
     * @param paramMap
     * @return
     * @throws Exception
     */
    @Override
    public HashMap<String, Object> selectListPaymentIntro(
            HashMap<String, Object> paramMap) throws Exception {
        log.debug("WebPaymentServiceImpl selectListPaymentIntro START");

        HashMap<String, Object> map = new HashMap<String, Object>();

        log.debug("loginMemberId       :"+paramMap.get("loginMemberId"));

        log.debug("menuClass           :"+paramMap.get("menuClass"));

        try{
            boolean check  = true;

            String menuClass    = String.valueOf(paramMap.get("menuClass"));

            // 정렬
            if(true != ValidationCheckUtil.emptyCheck(menuClass)){
                check = false;
                map.put("msgCode", Constants.FAIL);
                map.put("msgDesc","메뉴 정보가 없습니다.");
            }

            if(true == check){
                // 사용자 확인
                List<Map<String, Object>> userListMap = webMemberSqlMapDAO.checkMember(paramMap);
                int userListMapSize = userListMap.size();

                if(1==userListMapSize){
                    paramMap.put("menuClassAuthId", userListMap.get(0).get("muAuthId"));
                }
                else {
                    check = false;
                    map.put("msgCode", Constants.FAIL);
                    map.put("msgDesc", "사용자 정보가 올바르지 않습니다.");
                }
            }

            if(true == check){
                // 권한 조회
                HashMap<String, Object> authCheckParamMap = new HashMap<String, Object>();
                authCheckParamMap.put("menuClass",paramMap.get("menuClass"));
                authCheckParamMap.put("muAuthId",paramMap.get("menuClassAuthId"));
                List<Map<String, Object>> authMenuRelationlistMap = webAuthMenuRelationSqlMapDAO.selectAuthMenuRelation(authCheckParamMap);
                int authMenuRelationlistMapSize = authMenuRelationlistMap.size();

                if(1==authMenuRelationlistMapSize){
                    map.put("msgCode", Constants.OK);
                    map.put("success","true");

                    map.put("selectUseYn", authMenuRelationlistMap.get(0).get("selectUseYn"));
                    map.put("insertUseYn", authMenuRelationlistMap.get(0).get("insertUseYn"));
                    map.put("updateUseYn", authMenuRelationlistMap.get(0).get("updateUseYn"));
                    map.put("deleteUseYn", authMenuRelationlistMap.get(0).get("deleteUseYn"));
                    map.put("downloadUseYn", authMenuRelationlistMap.get(0).get("downloadUseYn"));
                }
                else {
                    map.put("msgCode", Constants.FAIL);
                    map.put("msgDesc", "권한 정보가 없습니다.");
                }
            }
        }
        catch(Exception e){
            e.printStackTrace();
            throw e;
        }
        log.debug("WebPaymentServiceImpl selectListPaymentIntro END");
        return map;
    }

    /**
     * 수납 리스트 조회
     *
     *
     * @param paramMap
     * @return
     * @throws Exception
     */
    @Override
    public HashMap<String, Object> selectListPayment(
            HashMap<String, Object> paramMap) throws Exception {
        log.debug("WebPaymentServiceImpl selectListPayment START");

        HashMap<String, Object> map = new HashMap<String, Object>();

        log.debug("loginMemberId       :"+paramMap.get("loginMemberId"));

        log.debug("menuClass           :"+paramMap.get("menuClass"));

        log.debug("paymentSearchKeywordParam  :"+paramMap.get("paymentSearchKeywordParam"));
        log.debug("paymentStart               :"+paramMap.get("paymentStart"));
        log.debug("paymentLimit               :"+paramMap.get("paymentLimit"));
        log.debug("paymentSort                :"+paramMap.get("paymentSort"));
        log.debug("paymentDir                 :"+paramMap.get("paymentDir"));
        log.debug("paymentCurrentPage         :"+paramMap.get("paymentCurrentPage"));

        log.debug("paymentSearchStartDate     :"+paramMap.get("paymentSearchStartDate"));
        log.debug("paymentSearchEndDate       :"+paramMap.get("paymentSearchEndDate"));

        List<Map<String, Object>> listMap = new ArrayList<Map<String,Object>>();

        try{
            boolean check  = true;

            if(true == check){
                // 사용자 확인
                List<Map<String, Object>> userListMap = webMemberSqlMapDAO.checkMember(paramMap);
                int userListMapSize = userListMap.size();

                if(1==userListMapSize){
                    paramMap.put("menuClassAuthId", userListMap.get(0).get("muAuthId"));
                }
                else {
                    check = false;
                    map.put("msgCode", Constants.FAIL);
                    map.put("msgDesc", "사용자 정보가 올바르지 않습니다.");
                }
            }
            if(true == check){
                // 권한 조회
                HashMap<String, Object> authCheckParamMap = new HashMap<String, Object>();
                authCheckParamMap.put("menuClass",paramMap.get("menuClass"));
                authCheckParamMap.put("muAuthId",paramMap.get("menuClassAuthId"));
                List<Map<String, Object>> authMenuRelationlistMap = webAuthMenuRelationSqlMapDAO.selectAuthMenuRelation(authCheckParamMap);

                if(1==authMenuRelationlistMap.size()){

                    if(("Y").equals(authMenuRelationlistMap.get(0).get("selectUseYn"))) {

                    }
                    else {
                        check = false;
                        map.put("msgCode", Constants.FAIL);
                        map.put("msgDesc", "조회 권한 정보가 없습니다.");
                    }
                }
                else {
                    check = false;
                    map.put("msgCode", Constants.FAIL);
                    map.put("msgDesc", "권한 정보가 없습니다.");
                }
            }
            if(true == check){
                // 정렬 
                if(null==paramMap.get("paymentDir")||("").equals(paramMap.get("paymentDir"))){

                }
                else{
                    String dir = String.valueOf(paramMap.get("paymentDir"));
                    if(("A").equals(dir)){
                        paramMap.put("paymentDir", "DESC");
                    }
                    else if(("B").equals(dir)){
                        paramMap.put("paymentDir", "ASC");
                    }
                    else {
                        paramMap.put("paymentDir", "DESC");
                    }
                }

                paramMap.put("useYn", "Y");

                if(("P").equals(paramMap.get("paymentStatus"))){
                    paramMap.put("paymentStatus2","NP");
                }
                List<Map<String, Object>> totalCountListMap = webPaymentSqlMapDAO.selectTotalPaymentCount(paramMap);
                int totalCount = Integer.parseInt(String.valueOf(totalCountListMap.get(0).get("totalCount")));

                if(0 < totalCount) {
                    // 리스트 조회
                    listMap = webPaymentSqlMapDAO.selectListPayment(paramMap);
                    map.put("groupByTreatment",webPaymentSqlMapDAO.selectGroupByTreatment(paramMap));
                    map.put("groupByPayment",webPaymentSqlMapDAO.selectGroupByPayment(paramMap));
                    map.put("groupByMembership",webPaymentSqlMapDAO.selectGroupByMembership(paramMap));
                    map.put("selectTotalAmount",webPaymentSqlMapDAO.selectTotalAmount(paramMap));
                    map.put("groupByCancel",webPaymentSqlMapDAO.selectCancelByPayment(paramMap));
                }

                map.put("msgCode", Constants.OK);
                map.put("success","true");
                map.put("totalCount", totalCount);
                map.put("rows",listMap);
            }
        }
        catch(Exception e){
            e.printStackTrace();
            throw e;
        }
        log.debug("WebPaymentServiceImpl selectListPayment END");
        return map;
    }

    @Override
    public List<Map<String, Object>> selectPaymentListExcel(
            HashMap<String, Object> paramMap) throws Exception {
        log.debug("WebPaymentServiceImpl selectPaymentListExcel START");

        HashMap<String, Object> map = new HashMap<String, Object>();
        List<Map<String, Object>> listMap = null;

        log.debug("loginMemberId       :"+paramMap.get("loginMemberId"));

        log.debug("menuClass           :"+paramMap.get("menuClass"));

        log.debug("paymentSearchKeywordParam  :"+paramMap.get("paymentSearchKeywordParam"));
        log.debug("paymentSort                :"+paramMap.get("paymentSort"));
        log.debug("paymentStart               :"+paramMap.get("paymentStart"));
        log.debug("paymentLimit               :"+paramMap.get("paymentLimit"));
        log.debug("paymentSort                :"+paramMap.get("paymentSort"));
        log.debug("paymentDir                 :"+paramMap.get("paymentDir"));
        log.debug("paymentCurrentPage         :"+paramMap.get("paymentCurrentPage"));

        log.debug("paymentSearchStartDate     :"+paramMap.get("paymentSearchStartDate"));
        log.debug("paymentSearchEndDate       :"+paramMap.get("paymentSearchEndDate"));
        try{
            boolean check  = true;

            if(true == check){
                // 사용자 확인
                List<Map<String, Object>> userListMap = webMemberSqlMapDAO.checkMember(paramMap);
                int userListMapSize = userListMap.size();

                if(1==userListMapSize){
                    paramMap.put("menuClassAuthId", userListMap.get(0).get("muAuthId"));
                }
                else {
                    check = false;
                    map.put("msgCode", Constants.FAIL);
                    map.put("msgDesc", "사용자 정보가 올바르지 않습니다.");
                }
            }

            if(true == check){
                // 권한 조회
                HashMap<String, Object> authCheckParamMap = new HashMap<String, Object>();
                authCheckParamMap.put("menuClass",paramMap.get("menuClass"));
                authCheckParamMap.put("muAuthId",paramMap.get("menuClassAuthId"));
                List<Map<String, Object>> authMenuRelationlistMap = webAuthMenuRelationSqlMapDAO.selectAuthMenuRelation(authCheckParamMap);

                if(1==authMenuRelationlistMap.size()){

                    if(("Y").equals(authMenuRelationlistMap.get(0).get("downloadUseYn"))) {

                    }
                    else {
                        check = false;
                        map.put("msgCode", Constants.FAIL);
                        map.put("msgDesc", "내려받기 권한 정보가 없습니다.");
                    }
                }
                else {
                    check = false;
                    map.put("msgCode", Constants.FAIL);
                    map.put("msgDesc", "권한 정보가 없습니다.");
                }
            }

            if(true == check){
                listMap = webPaymentSqlMapDAO.selectListPayment(paramMap);
            }

        }catch(Exception e){
            e.printStackTrace();
            throw e;
        }

        log.debug("WebUserServiceImpl selectPaymentListExcel END");
        return listMap;
    }

	/**
	 * 고객 수납내역 정보 조회 (List)
	 *
	 *
	 * @param paramMap
	 * @return
	 * @throws Exception
	 */
	@Override
	public HashMap<String, Object> selectListPaymentUser(
			HashMap<String, Object> paramMap) throws Exception {
		log.debug("WebPaymentServiceImpl selectListPaymentUser START");
		
		HashMap<String, Object> map = new HashMap<String, Object>();
		
		log.debug("loginMemberId       :"+paramMap.get("loginMemberId"));
		
		log.debug("menuClass           :"+paramMap.get("menuClass"));
		
		log.debug("muUserId            :"+paramMap.get("muUserId"));
		
		// 검색
		log.debug("startDate           :"+paramMap.get("startDate"));
		log.debug("endDate             :"+paramMap.get("endDate"));
		log.debug("searchKeyword       :"+paramMap.get("searchKeyword"));
		log.debug("muPaymentId         :"+paramMap.get("muPaymentId"));
		log.debug("paymentNumber       :"+paramMap.get("paymentNumber"));

		try{
			boolean check  = true;
			String muPaymentId    = String.valueOf(paramMap.get("muUserId"));
			
			// 정렬
			if(true != ValidationCheckUtil.emptyCheck(muPaymentId)){
				check = false;
				map.put("msgCode", Constants.FAIL);
				map.put("msgDesc","사용자 정보가 없습니다.");
			}
			
			if(true == check){
				// 사용자 확인
				List<Map<String, Object>> userListMap = webMemberSqlMapDAO.checkMember(paramMap);
				int userListMapSize = userListMap.size();
				
				if(1 == userListMapSize){
					paramMap.put("menuClassAuthId", userListMap.get(0).get("muAuthId"));
				}
				else {
					check = false;
					map.put("msgCode", Constants.FAIL);
					map.put("msgDesc", "사용자 정보가 올바르지 않습니다.");
				}
			}
            if(true == check){
                // 권한 조회
                HashMap<String, Object> authCheckParamMap = new HashMap<String, Object>();
                authCheckParamMap.put("menuClass",paramMap.get("menuClass"));
                authCheckParamMap.put("muAuthId",paramMap.get("menuClassAuthId"));
                List<Map<String, Object>> authMenuRelationlistMap = webAuthMenuRelationSqlMapDAO.selectAuthMenuRelation(authCheckParamMap);

                if(1==authMenuRelationlistMap.size()){

                    if(("Y").equals(authMenuRelationlistMap.get(0).get("selectUseYn"))) {

                    }
                    else {
                        check = false;
                        map.put("msgCode", Constants.FAIL);
                        map.put("msgDesc", "조회 권한 정보가 없습니다.");
                    }
                }
                else {
                    check = false;
                    map.put("msgCode", Constants.FAIL);
                    map.put("msgDesc", "권한 정보가 없습니다.");
                }
            }
			
			if(true == check){
				List<Map<String, Object>> listMap = webPaymentSqlMapDAO.selectListPaymentUser(paramMap);
				List<Map<String, Object>> listMap2 = webPaymentSqlMapDAO.selectListPaymentProcedureDetail(paramMap);
				List<Map<String, Object>> listMap3 = webPaymentSqlMapDAO.selectListPaymentDetail(paramMap);

				map.put("msgCode", Constants.OK);
				map.put("success","true");
				map.put("rows",listMap);
				map.put("procedureList",listMap2);
				map.put("paymentDetail",listMap3);
			}
		}
		catch(Exception e){
			e.printStackTrace();
			throw e;
		}
		log.debug("WebPaymentServiceImpl selectListPaymentUser END");
		return map;
	}
	

    /**
     * 고객 - 수납 내역 리스트 화면으로 이동.
     *
     *
     * @param paramMap
     * @return
     * @throws Exception
     */
    @Override
    public HashMap<String, Object> selectListPaymentUser2Intro(
            HashMap<String, Object> paramMap) throws Exception {
        log.debug("WebPaymentServiceImpl selectListPaymentUser2Intro START");

        HashMap<String, Object> map = new HashMap<String, Object>();

        log.debug("loginMemberId       :"+paramMap.get("loginMemberId"));

        log.debug("menuClass           :"+paramMap.get("menuClass"));
        
        log.debug("muUserId            :"+paramMap.get("muUserId"));

        try{
            boolean check  = true;

            String menuClass    = String.valueOf(paramMap.get("menuClass"));

            // 정렬
            if(true != ValidationCheckUtil.emptyCheck(menuClass)){
                check = false;
                map.put("msgCode", Constants.FAIL);
                map.put("msgDesc","메뉴 정보가 없습니다.");
            }

            if(true == check){
                // 사용자 확인
                List<Map<String, Object>> userListMap = webMemberSqlMapDAO.checkMember(paramMap);
                int userListMapSize = userListMap.size();

                if(1==userListMapSize){
                    paramMap.put("menuClassAuthId", userListMap.get(0).get("muAuthId"));
                }
                else {
                    check = false;
                    map.put("msgCode", Constants.FAIL);
                    map.put("msgDesc", "사용자 정보가 올바르지 않습니다.");
                }
            }

            if(true == check){
                // 권한 조회
                HashMap<String, Object> authCheckParamMap = new HashMap<String, Object>();
                authCheckParamMap.put("menuClass",paramMap.get("menuClass"));
                authCheckParamMap.put("muAuthId",paramMap.get("menuClassAuthId"));
                List<Map<String, Object>> authMenuRelationlistMap = webAuthMenuRelationSqlMapDAO.selectAuthMenuRelation(authCheckParamMap);
                int authMenuRelationlistMapSize = authMenuRelationlistMap.size();

                if(1==authMenuRelationlistMapSize){
                    map.put("msgCode", Constants.OK);
                    map.put("success","true");

                    map.put("selectUseYn", authMenuRelationlistMap.get(0).get("selectUseYn"));
                    map.put("insertUseYn", authMenuRelationlistMap.get(0).get("insertUseYn"));
                    map.put("updateUseYn", authMenuRelationlistMap.get(0).get("updateUseYn"));
                    map.put("deleteUseYn", authMenuRelationlistMap.get(0).get("deleteUseYn"));
                    map.put("downloadUseYn", authMenuRelationlistMap.get(0).get("downloadUseYn"));
                }
                else {
                    map.put("msgCode", Constants.FAIL);
                    map.put("msgDesc", "권한 정보가 없습니다.");
                }
            }
        }
        catch(Exception e){
            e.printStackTrace();
            throw e;
        }
        log.debug("WebPaymentServiceImpl selectListPaymentUser2Intro END");
        return map;
    }

    /**
     * 고객 - 수납 내역 리스트 조회 (List)
     *
     *
     * @param paramMap
     * @return
     * @throws Exception
     */
    @Override
    public HashMap<String, Object> selectListPaymentUser2(
            HashMap<String, Object> paramMap) throws Exception {
        log.debug("WebPaymentServiceImpl selectListPaymentUser2 START");

        HashMap<String, Object> map = new HashMap<String, Object>();

        log.debug("loginMemberId       :"+paramMap.get("loginMemberId"));

        log.debug("menuClass           :"+paramMap.get("menuClass"));
        
        log.debug("muUserId              :"+paramMap.get("muUserId"));

        log.debug("paymentSearchKeywordParam    :"+paramMap.get("paymentSearchKeywordParam"));
        log.debug("paymentSort                  :"+paramMap.get("paymentSort"));
        log.debug("paymentStart          :"+paramMap.get("paymentStart"));
        log.debug("paymentLimit          :"+paramMap.get("paymentLimit"));
        log.debug("paymentSort           :"+paramMap.get("paymentSort"));
        log.debug("paymentDir            :"+paramMap.get("paymentDir"));

        log.debug("paymentSearchStartDate       :"+paramMap.get("paymentSearchStartDate"));
        log.debug("paymentSearchEndDate         :"+paramMap.get("paymentSearchEndDate"));
        log.debug("muTreatmentId                :"+paramMap.get("muTreatmentId"));
        log.debug("paymentCategoryItemNm        :"+paramMap.get("paymentCategoryItemNm"));

        List<Map<String, Object>> listMap = new ArrayList<Map<String,Object>>();

        try{
            boolean check  = true;

            if(true == check){
                // 사용자 확인
                List<Map<String, Object>> userListMap = webMemberSqlMapDAO.checkMember(paramMap);
                int userListMapSize = userListMap.size();

                if(1==userListMapSize){
                    paramMap.put("menuClassAuthId", userListMap.get(0).get("muAuthId"));
                }
                else {
                    check = false;
                    map.put("msgCode", Constants.FAIL);
                    map.put("msgDesc", "사용자 정보가 올바르지 않습니다.");
                }
            }
            if(true == check){
                // 권한 조회
                HashMap<String, Object> authCheckParamMap = new HashMap<String, Object>();
                authCheckParamMap.put("menuClass",paramMap.get("menuClass"));
                authCheckParamMap.put("muAuthId",paramMap.get("menuClassAuthId"));
                List<Map<String, Object>> authMenuRelationlistMap = webAuthMenuRelationSqlMapDAO.selectAuthMenuRelation(authCheckParamMap);
                int authMenuRelationlistMapSize = authMenuRelationlistMap.size();

                if(1==authMenuRelationlistMapSize){

                    if(("Y").equals(authMenuRelationlistMap.get(0).get("selectUseYn"))) {

                    }
                    else {
                        check = false;
                        map.put("msgCode", Constants.FAIL);
                        map.put("msgDesc", "조회 권한 정보가 없습니다.");
                    }
                }
                else {
                    check = false;
                    map.put("msgCode", Constants.FAIL);
                    map.put("msgDesc", "권한 정보가 없습니다.");
                }
            }
            if(true == check){
                // 정렬 
                if(null==paramMap.get("dir")||("").equals(paramMap.get("dir"))){

                }
                else{
                    String dir = String.valueOf(paramMap.get("dir"));
                    if(("A").equals(dir)){
                        paramMap.put("dir", "DESC");
                    }
                    else if(("B").equals(dir)){
                        paramMap.put("dir", "ASC");
                    }
                    else {
                        paramMap.put("dir", "DESC");
                    }
                }

                paramMap.put("useYn", "Y");

                List<Map<String, Object>> totalCountListMap = webPaymentSqlMapDAO.selectTotalPaymentCount(paramMap);
                int totalCount = Integer.parseInt(String.valueOf(totalCountListMap.get(0).get("totalCount")));

                if(0 < totalCount) {
                    // 리스트 조회
                    listMap = webPaymentSqlMapDAO.selectListPayment(paramMap);
                }

                map.put("msgCode", Constants.OK);
                map.put("success","true");
                map.put("totalCount", totalCount);
                map.put("rows",listMap);
            }
        }
        catch(Exception e){
            e.printStackTrace();
            throw e;
        }
        log.debug("WebPaymentServiceImpl selectListPaymentUser2 END");
        return map;
    }

    /**
     * 고객 - 수납 내역 리스트 조회 (List, Excel)
     *
     *
     * @param paramMap
     * @return
     * @throws Exception
     */
    @Override
    public List<Map<String, Object>> selectListPaymentUser2Excel(
            HashMap<String, Object> paramMap) throws Exception {
        log.debug("WebPaymentServiceImpl selectListPaymentUser2Excel START");

        HashMap<String, Object> map = new HashMap<String, Object>();

        log.debug("loginMemberId       :"+paramMap.get("loginMemberId"));

        log.debug("menuClass           :"+paramMap.get("menuClass"));
        
        log.debug("muUserId              :"+paramMap.get("muUserId"));

        log.debug("searchKeywordParam    :"+paramMap.get("searchKeywordParam"));
        log.debug("sort                  :"+paramMap.get("sort"));
        log.debug("start                 :"+paramMap.get("start"));
        log.debug("limit                 :"+paramMap.get("limit"));
        log.debug("sort                  :"+paramMap.get("sort"));
        log.debug("dir                   :"+paramMap.get("dir"));
        log.debug("currentPage           :"+paramMap.get("currentPage"));

        log.debug("searchStartDate       :"+paramMap.get("searchStartDate"));
        log.debug("searchEndDate         :"+paramMap.get("searchEndDate"));
        log.debug("muTreatmentId         :"+paramMap.get("muTreatmentId"));
        log.debug("paymentCategoryItemNm :"+paramMap.get("paymentCategoryItemNm"));

        List<Map<String, Object>> listMap = new ArrayList<Map<String,Object>>();

        try{
            boolean check  = true;

            if(true == check){
                // 사용자 확인
                List<Map<String, Object>> userListMap = webMemberSqlMapDAO.checkMember(paramMap);
                int userListMapSize = userListMap.size();

                if(1==userListMapSize){
                    paramMap.put("menuClassAuthId", userListMap.get(0).get("muAuthId"));
                }
                else {
                    check = false;
                    map.put("msgCode", Constants.FAIL);
                    map.put("msgDesc", "사용자 정보가 올바르지 않습니다.");
                }
            }
            if(true == check){
                // 권한 조회
                HashMap<String, Object> authCheckParamMap = new HashMap<String, Object>();
                authCheckParamMap.put("menuClass",paramMap.get("menuClass"));
                authCheckParamMap.put("muAuthId",paramMap.get("menuClassAuthId"));
                List<Map<String, Object>> authMenuRelationlistMap = webAuthMenuRelationSqlMapDAO.selectAuthMenuRelation(authCheckParamMap);
                int authMenuRelationlistMapSize = authMenuRelationlistMap.size();

                if(1==authMenuRelationlistMapSize){

                    if(("Y").equals(authMenuRelationlistMap.get(0).get("downloadUseYn"))) {

                    }
                    else {
                        check = false;
                        map.put("msgCode", Constants.FAIL);
                        map.put("msgDesc", "내려받기 권한 정보가 없습니다.");
                    }
                }
                else {
                    check = false;
                    map.put("msgCode", Constants.FAIL);
                    map.put("msgDesc", "권한 정보가 없습니다.");
                }
            }

            if(true == check){
                // 정렬 
                if(null==paramMap.get("dir")||("").equals(paramMap.get("dir"))){

                }
                else{
                    String dir = String.valueOf(paramMap.get("dir"));
                    if(("A").equals(dir)){
                        paramMap.put("dir", "DESC");
                    }
                    else if(("B").equals(dir)){
                        paramMap.put("dir", "ASC");
                    }
                    else {
                        paramMap.put("dir", "DESC");
                    }
                }

                paramMap.put("useYn", "Y");

                // 리스트 조회
                listMap = webPaymentSqlMapDAO.selectListPaymentUser2Excel(paramMap);
            }
        }
        catch(Exception e){
            e.printStackTrace();
            throw e;
        }
        log.debug("WebPaymentServiceImpl selectListPaymentUser2Excel END");
        return listMap;
    }

    /**
     * 결제 정보 등록
     *
     * @param paramMap
     * @return
     * @throws Exception
     */
    @Override
    @Transactional(rollbackFor={Exception.class}, propagation = Propagation.REQUIRES_NEW)
    public HashMap<String, Object> insertPayment(
            HashMap<String, Object> paramMap) throws Exception{
        log.debug("WebPaymentServiceImpl insertPayment START");

        HashMap<String, Object> map = new HashMap<String, Object>();

        log.debug("loginMemberId       :"+paramMap.get("loginMemberId"));

        log.debug("menuClass           :"+paramMap.get("menuClass"));

        log.debug("treatmentName       :"+paramMap.get("treatmentName"));

        try{
            boolean check  = true;
            String tId = String.valueOf(System.currentTimeMillis());
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd");
            Calendar c1 = Calendar.getInstance();
            String tDate = sdf.format(c1.getTime());
            String tDate2 = sdf2.format(c1.getTime());

            if(true == check){
                // 사용자 확인
                List<Map<String, Object>> userListMap = webMemberSqlMapDAO.checkMember(paramMap);
                int userListMapSize = userListMap.size();

                if(1==userListMapSize){
                    paramMap.put("menuClassAuthId", userListMap.get(0).get("muAuthId"));
                }
                else {
                    check = false;
                    map.put("msgCode", Constants.FAIL);
                    map.put("msgDesc", "사용자 정보가 올바르지 않습니다.");
                }
            }
            if(true == check){
                // 권한 조회
                HashMap<String, Object> authCheckParamMap = new HashMap<String, Object>();
                authCheckParamMap.put("menuClass",paramMap.get("menuClass"));
                authCheckParamMap.put("muAuthId",paramMap.get("menuClassAuthId"));
                List<Map<String, Object>> authMenuRelationlistMap = webAuthMenuRelationSqlMapDAO.selectAuthMenuRelation(authCheckParamMap);
                int authMenuRelationlistMapSize = authMenuRelationlistMap.size();

                if(1==authMenuRelationlistMapSize){

                    if(("Y").equals(authMenuRelationlistMap.get(0).get("insertUseYn"))) {
                    }
                    else {
                        check = false;
                        map.put("msgCode", Constants.FAIL);
                        map.put("msgDesc", "등록 권한 정보가 없습니다.");
                    }
                }
                else {
                    check = false;
                    map.put("msgCode", Constants.FAIL);
                    map.put("msgDesc", "권한 정보가 없습니다.");
                }
            }





            if(true == check){
                paramMap.put("tDate", tDate);
                paramMap.put("tId", tId);
                paramMap.put("muMemberId", paramMap.get("loginMemberId"));

                String reserveData          = String.valueOf(paramMap.get("reserveData"));
                String paymentData          = String.valueOf(paramMap.get("paymentData"));
                String detailData           = String.valueOf(paramMap.get("detailData"));

                JSONParser parser = new JSONParser();
                //예약테이블 상태 변경
                if(true == ValidationCheckUtil.emptyCheck(reserveData)) {
                    Object reserveObj = parser.parse( reserveData );
                    JSONArray reserveDataArray = (JSONArray) reserveObj;
                    for (Object reserveDataObj : reserveDataArray) {
                        JSONObject jsonObject = (JSONObject) reserveDataObj;
                        HashMap<String, Object> dataMap = new HashMap<>();
                        dataMap.put("muReserveId", jsonObject.get("muReserveId"));
                        dataMap.put("status", jsonObject.get("status2"));
                        dataMap.put("modId", paramMap.get("modId"));
                        webReserveSqlMapDAO.updateReserveStatus2(dataMap);
                    }
                }

                //수납정보 테이블 등록
                if(true == ValidationCheckUtil.emptyCheck(paymentData)) {
                    Object paymentObj = parser.parse( paymentData );
                    JSONArray paymentDataObj = (JSONArray) paymentObj;;
                    for (int i = 0; i < paymentDataObj.size(); i++) {
                        JSONObject jsonObject = (JSONObject) paymentDataObj.get(i);
                        HashMap<String, Object> dataMap = new HashMap<>();
                        String muPaymentId = ("PMT").concat(String.valueOf(System.currentTimeMillis()));

                        //미수납 및 부분결제 이전 결제번호 조회
                        if(ValidationCheckUtil.emptyCheck((String) jsonObject.get("muPaymentId"))){
                            dataMap.put("id", jsonObject.get("muPaymentId"));
                            dataMap.put("paymentAmount", jsonObject.get("paymentAmount"));
                            dataMap.put("paymentCategoryItemId", jsonObject.get("paymentCategoryItemId"));
                            List<Map<String, Object>> tempListMap = webPaymentSqlMapDAO.selectPaymentNumber(dataMap);
                            dataMap.put("paymentNumber", tempListMap.getFirst().get("paymentNumber"));
                            dataMap.put("status", tempListMap.getFirst().get("status"));
                        }else {
                            dataMap.put("paymentNumber", jsonObject.get("paymentNumber"));
                            dataMap.put("status",jsonObject.get("status") );
                        }

                        // 환불 및 취소인지 확인
                        List<Map<String, Object>> listMap = webPaymentSqlMapDAO.selectPaymentPaymentNumber(dataMap);
                        int listMapSize = listMap.size();

                        if(0<listMapSize){
                            String cancelYn = String.valueOf(listMap.get(0).get("cancelYn"));

                            if(("N").equals(cancelYn)){
                                check = false;
                                map.put("msgCode", Constants.FAIL);
                                map.put("msgDesc", "결제취소 및 환불된 건입니다.");

                                return map;
                            }
                        }

                        dataMap.put("muPaymentId", muPaymentId);
                        dataMap.put("paymentApprovalId", jsonObject.get("paymentApprovalId"));
                        dataMap.put("muUserId", jsonObject.get("muUserId"));
                        dataMap.put("paymentCategoryItemId", jsonObject.get("paymentCategoryItemId"));
                        dataMap.put("paymentCategoryItemName", jsonObject.get("paymentCategoryItemName"));
                        dataMap.put("paymentCardInfo", jsonObject.get("paymentCardInfo"));
                        dataMap.put("cardInstallments", jsonObject.get("cardInstallments"));
                        dataMap.put("cardInstallmentsCode", jsonObject.get("cardInstallmentsCode"));
                        dataMap.put("muMemberId", paramMap.get("muMemberId"));
                        dataMap.put("etc", jsonObject.get("etc"));
                        dataMap.put("refundEtc", jsonObject.get("refundEtc"));
                        dataMap.put("refundAccount", jsonObject.get("refundAccount"));
                        dataMap.put("amount", jsonObject.get("amount"));
                        dataMap.put("vat", jsonObject.get("vat"));
                        dataMap.put("paymentAmount", jsonObject.get("paymentAmount"));
                        dataMap.put("refundAmount", jsonObject.get("refundAmount"));
                        dataMap.put("firstVisitYn",jsonObject.get("firstVisitYn"));
                        dataMap.put("muPaymentRequestHistoryId",jsonObject.get("muPaymentRequestHistoryId"));
                        dataMap.put("muPaymentResponseHistoryId",jsonObject.get("muPaymentResponseHistoryId"));
                        dataMap.put("modId", paramMap.get("modId"));
                        dataMap.put("regId", paramMap.get("modId"));
                        dataMap.put("tId", paramMap.get("tId"));
                        dataMap.put("tDate", paramMap.get("tDate"));
                        webPaymentSqlMapDAO.insertPayment(dataMap);

                        //멤버십 적용 후 분할결제 시
                         if (i == 0) {
                            paramMap.put("muPaymentId", dataMap.get("id"));
                        } else {
                            paramMap.put("muPaymentId2", dataMap.get("id"));
                        }
                        paramMap.put("paymentNumber", dataMap.get("paymentNumber"));
                        paramMap.put("muUserId", dataMap.get("muUserId"));
                        paramMap.put("etc",dataMap.get("etc"));
                    }
                }
                //수납상세정보 테이블 등록 / 재고 차감
                if(true == ValidationCheckUtil.emptyCheck(detailData)) {
                    Object detailObj = parser.parse( detailData );
                    JSONArray detailDataArray = (JSONArray) detailObj;
                    int usedMembership = 0;
                    for (Object detailDataObj : detailDataArray) {
                        JSONObject jsonObject = (JSONObject) detailDataObj;
                        HashMap<String, Object> treatmentProcedureMap = new HashMap<String, Object>();
                        treatmentProcedureMap.put("muUserId",paramMap.get("muUserId"));
                        treatmentProcedureMap.put("muTreatmentProcedureId",jsonObject.get("muTreatmentProcedureId"));

                        //시술 사용 제품 정보 조회
                        List<Map<String, Object>> treatmentProcedureProductList = webTreatmentProcedureProductSqlMapDAO.selectTreatmentProcedureProduct(treatmentProcedureMap);
                        HashMap<String, Object> productDataMap = new HashMap<>();
                        for (Map<String, Object> stringObjectMap : treatmentProcedureProductList) {

                            double intQuantity = Double.parseDouble(String.valueOf(stringObjectMap.get("useQuantity")));

                            productDataMap.put("muTreatmentId", stringObjectMap.get("muTreatmentId"));
                            productDataMap.put("treatmentName", stringObjectMap.get("treatmentName"));
                            productDataMap.put("muCompanyId", stringObjectMap.get("muCompanyId"));
                            productDataMap.put("muProductId", stringObjectMap.get("muProductId"));
                            productDataMap.put("productName", stringObjectMap.get("productName"));
                            productDataMap.put("productCode", stringObjectMap.get("productCode"));
                            productDataMap.put("inOutDate", paramMap.get("tDate"));
                            productDataMap.put("type", 'U');
                            productDataMap.put("etc", stringObjectMap.get("etc"));
                            productDataMap.put("regId", paramMap.get("regId"));
                            productDataMap.put("modId", paramMap.get("modId"));


                            List<Map<String, Object>> stockSumListMap = webStockSumSqlMapDAO.selectListStockSum(productDataMap);
                            for (Map<String, Object> stockItem : stockSumListMap) {

                                double stockQuantity = Double.parseDouble(String.valueOf(stockItem.get("quantity")));

                                // 재고가 없는 경우
                                if (stockQuantity <= 0) {
                                    continue;
                                }
                                double insertQuantity = Math.min(stockQuantity, intQuantity);
                                String muStockHistoryId = ("SH").concat(String.valueOf(System.currentTimeMillis()));
                                productDataMap.put("muStockHistoryId2", (String)stockItem.get("muStockHistoryId"));
                                productDataMap.put("muStockHistoryId", muStockHistoryId);
                                productDataMap.put("quantity", insertQuantity);
                                productDataMap.put("companyName", stockItem.get("companyName"));
                                productDataMap.put("price", stockItem.get("price"));
                                //재고 이력 테이블 등록
                                webStockHistorySqlMapDAO.insertStockHistory(productDataMap);

                                log.debug("muStockHistoryId :" + productDataMap.get("id"));
                                paramMap.put("muStockHistoryId", productDataMap.get("id"));
                                map.put("muStockHistoryId", paramMap.get("muStockHistoryId"));

                                String muStockSumId = String.valueOf(stockItem.get("muStockSumId"));
                                double remainingQuantity = stockQuantity - insertQuantity;

                                HashMap<String, Object> stockSumParamMap = new HashMap<String, Object>();
                                stockSumParamMap.put("muStockSumId", muStockSumId);
                                stockSumParamMap.put("quantity", remainingQuantity);
                                stockSumParamMap.put("modId", paramMap.get("modId"));

                                //현 재고 수량 업데이트
                                webStockSumSqlMapDAO.updateStockSum(stockSumParamMap);

                                // 등록한 수량 빼고 다음 값 확인
                                intQuantity -= insertQuantity;

                                // 수량만큼 등록햇으면 종료
                                if (intQuantity == 0) {
                                    break;
                                }
                            }
                            // 차감 수량이 부족한 경우 최근 입고 된 재고 데이터 기준 마이너스 수량 입력(재고가 음수로 들어가는 경우)
                            if (intQuantity > 0) {
                                String muStockHistoryId = ("SH").concat(String.valueOf(System.currentTimeMillis()));
                                productDataMap.put("muStockHistoryId2", stringObjectMap.get("stockStockHistoryId"));
                                productDataMap.put("muStockHistoryId", muStockHistoryId);
                                productDataMap.put("quantity", intQuantity);
                                productDataMap.put("companyName", stringObjectMap.get("companyName"));
                                productDataMap.put("price", stringObjectMap.get("price"));
                                webStockHistorySqlMapDAO.insertStockHistory(productDataMap);
                                log.debug("muStockHistoryId :" + productDataMap.get("id"));
                                paramMap.put("muStockHistoryId", productDataMap.get("id"));
                                map.put("muStockHistoryId", paramMap.get("muStockHistoryId"));
                                HashMap<String, Object> stockParamMap = new HashMap<String, Object>();
                                stockParamMap.put("muStockSumId", stringObjectMap.get("muStockSumId"));
                                double lastRemainingQuantity = Double.parseDouble(String.valueOf(stringObjectMap.get("quantity"))) - intQuantity;
                                stockParamMap.put("quantity", lastRemainingQuantity);
                                stockParamMap.put("modId", paramMap.get("modId"));
                                webStockSumSqlMapDAO.updateStockSum(stockParamMap);
                            }
                        }

                        HashMap<String, Object> dataMap = new HashMap<>();
                        HashMap<String, Object> dataMap2 = new HashMap<>();
                        String muPaymentDetailId = ("PMD").concat(String.valueOf(System.currentTimeMillis()));
                        dataMap.put("muPaymentDetailId", muPaymentDetailId);

//                        int amount = getIntFromJson(jsonObject, "amount");
//                        int vat = getIntFromJson(jsonObject, "vat");
//                        int totalAmount = getIntFromJson(jsonObject, "totalAmount");
//                        int discountAmount = getIntFromJson(jsonObject, "discountAmount");
                        int membershipPrice = getIntFromJson(jsonObject, "membershipPrice");

                        //결제 금액이 0원인 경우
//                        if (0 == amount && 0 == vat && 0 == totalAmount && 0 == discountAmount && 0 == membershipPrice) {
//                            continue;
//                        }

                        if (paramMap.containsKey("muPaymentId2")) {
                            insertPaymentDetail(dataMap, paramMap, jsonObject,  true);
                            insertAdditionalPaymentDetail(dataMap2, paramMap, jsonObject);
                        } else {
                            insertPaymentDetail(dataMap, paramMap, jsonObject,  false);
                        }

                        if (membershipPrice < 0) {
                            HashMap<String, Object> dataMap3 = new HashMap<>();
                            //멤버십 내역 추가
                            String muMembershipHistoryId = ("M").concat(String.valueOf(System.currentTimeMillis()));
                            dataMap3.put("muMembershipHistoryId", muMembershipHistoryId);
                            dataMap3.put("muUserId", paramMap.get("muUserId"));
                            dataMap3.put("muMemberId", paramMap.get("muMemberId"));
                            dataMap3.put("muTreatmentId", jsonObject.get("muTreatmentId"));
                            dataMap3.put("reserveMemberId", jsonObject.get("reserveMemberId"));
                            dataMap3.put("muTreatmentProcedureId", jsonObject.get("muTreatmentProcedureId"));
                            dataMap3.put("memo", paramMap.get("etc"));
                            dataMap3.put("usedAmount", Math.abs(Integer.parseInt("" + jsonObject.get("membershipPrice"))));
                            dataMap3.put("regId", paramMap.get("regId"));
                            dataMap3.put("modId", paramMap.get("modId"));
                            dataMap3.put("tId", paramMap.get("tId"));
                            dataMap3.put("usageType", "U");
                            webMembershipSqlMapDAO.insertMembershipHistory(dataMap3);

                            usedMembership += membershipPrice;
                        }
                    }
                    paramMap.put("usedMembership", usedMembership);
                }
                //멤버십 잔액 업데이트
                if(ValidationCheckUtil.emptyCheck((String) paramMap.get("membershipBalance"))){
                    HashMap<String, Object> dataMap = new HashMap<>();
                    dataMap.put("lastUseDate", paramMap.get("tDate"));
                    dataMap.put("membershipBalance", paramMap.get("membershipBalance"));
                    dataMap.put("tId", paramMap.get("tId"));
                    dataMap.put("tDate", paramMap.get("tDate"));
                    dataMap.put("modId", paramMap.get("modId"));
                    dataMap.put("muUserId", paramMap.get("muUserId"));
                    webMembershipSqlMapDAO.updateMembership(dataMap);




                    // 고객 조회
                    List<Map<String, Object>> userListMap = webUserSqlMapDAO.selectUser(paramMap);
                    paramMap.put("userName", userListMap.get(0).get("userName"));
                    paramMap.put("phoneNumber", userListMap.get(0).get("phoneNumber"));

                    // 자동발송 (알림톡 + 푸시)
                    // 템플릿 조회
                    HashMap<String, Object> insertKakaoMap = new HashMap<String, Object>();
                    insertKakaoMap.put("templateCode", "024110000528");
                    List<Map<String, Object>> templateListMap = webKakaoTemplateSqlMapDAO.selectKakaoTemplate(insertKakaoMap);

                    // 디바이스 리스트 조회
                    List<Map<String, Object>> deviceListMap = webDeviceSqlMapDAO.selectListDevice2(paramMap);
                    int deviceListMapSize = deviceListMap.size();

                    // 고객명, 예약날짜, 예약시간, 시술명
                    String KakaoTemplateTitle = String.valueOf(templateListMap.get(0).get("title"));
                    String KakaoTemplateContent = String.valueOf(templateListMap.get(0).get("content"));



                    // 자동발송 (알림톡 + 푸시)
                    // 고객명, 멤버십사용날짜, 멤버쉽사용금액, 멤버십잔액
                    String kakaoContent = KakaoTemplateContent;
                    kakaoContent = kakaoContent.replace("#{고객명}", String.valueOf(paramMap.get("userName")));
                    kakaoContent = kakaoContent.replace("#{멤버십사용날짜}", tDate2);
                    kakaoContent = kakaoContent.replace("#{멤버쉽사용금액}", String.valueOf(paramMap.get("usedMembership")));
                    kakaoContent = kakaoContent.replace("#{멤버십잔액}", String.valueOf(paramMap.get("membershipBalance")));


                    insertKakaoMap.put("muKakaoId", ("K").concat(String.valueOf(System.currentTimeMillis())));
                    insertKakaoMap.put("muUserId", paramMap.get("muUserId"));
                    insertKakaoMap.put("userName", paramMap.get("userName"));
                    insertKakaoMap.put("phoneNumber", paramMap.get("phoneNumber"));
                    insertKakaoMap.put("content", kakaoContent);
                    insertKakaoMap.put("state", "R");
                    insertKakaoMap.put("popbillState", "0");
                    insertKakaoMap.put("sender", senderPhoneNumber);
                    insertKakaoMap.put("regId", "SYSTEM");
                    insertKakaoMap.put("modId", "SYSTEM");
                    insertKakaoMap.put("tId", paramMap.get("tId"));
                    insertKakaoMap.put("tDate", paramMap.get("tDate"));

                    webKakaoSqlMapDAO.insertKakao(insertKakaoMap);
//                    autoKakaoService.send("membershipUse", insertKakaoMap);

                    // 푸시
                    if(0<deviceListMapSize){
                        HashMap<String, Object> insertPushMap = new HashMap<String, Object>();
                        for(int j=0; j<deviceListMapSize; j++){
                            insertPushMap.put("muPushId", ("P").concat(String.valueOf(System.currentTimeMillis())));
                            insertPushMap.put("muUserId", paramMap.get("muUserId"));
                            insertPushMap.put("userName", paramMap.get("userName"));
                            insertPushMap.put("muDeviceId", deviceListMap.get(j).get("muDeviceId"));
                            insertPushMap.put("deviceUuid", deviceListMap.get(j).get("deviceUuid"));
                            insertPushMap.put("pushKey", deviceListMap.get(j).get("pushKey"));
                            insertPushMap.put("pushType", "A");
                            insertPushMap.put("phoneType", deviceListMap.get(j).get("phoneType"));
                            insertPushMap.put("title", KakaoTemplateTitle);
                            insertPushMap.put("content", kakaoContent);
                            insertPushMap.put("state", "R");
                            insertPushMap.put("regId", "SYSTEM");
                            insertPushMap.put("modId", "SYSTEM");
                            insertPushMap.put("tId", paramMap.get("tId"));
                            insertPushMap.put("tDate", paramMap.get("tDate"));

                            webPushSqlMapDAO.insertPush(insertPushMap);
//                            autoPushService.send("membershipUse", insertPushMap);
                        }
                    }
                }

                log.debug("muPaymentId :"+paramMap.get("muPaymentId"));
                paramMap.put("muPaymentId", paramMap.get("muPaymentId"));
                map.put("muPaymentId", paramMap.get("muPaymentId"));

                map.put("msgCode", Constants.OK);
                map.put("msgDesc", "등록되었습니다.");
            }
        }
        catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
        log.debug("WebPaymentServiceImpl insertPayment END");
        return map;
    }

    /**
     * 단말 결제요청 정보 등록
     *
     * @param paramMap
     * @return
     * @throws Exception
     */
    @Override
    @Transactional(rollbackFor={Exception.class}, propagation = Propagation.REQUIRES_NEW)
    public HashMap<String, Object> insertPaymentRequestHistory(
            HashMap<String, Object> paramMap) throws Exception{
        log.debug("WebPaymentServiceImpl insertPaymentRequestHistory START");

        HashMap<String, Object> map = new HashMap<String, Object>();

        log.debug("loginMemberId       :"+paramMap.get("loginMemberId"));

        log.debug("menuClass           :"+paramMap.get("menuClass"));

        log.debug("treatmentName       :"+paramMap.get("treatmentName"));

        try{
            boolean check  = true;
            String tId = String.valueOf(System.currentTimeMillis());
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Calendar c1 = Calendar.getInstance();
            String tDate = sdf.format(c1.getTime());

            if(true == check){
                // 사용자 확인
                List<Map<String, Object>> userListMap = webMemberSqlMapDAO.checkMember(paramMap);
                int userListMapSize = userListMap.size();

                if(1==userListMapSize){
                    paramMap.put("menuClassAuthId", userListMap.get(0).get("muAuthId"));
                }
                else {
                    check = false;
                    map.put("msgCode", Constants.FAIL);
                    map.put("msgDesc", "사용자 정보가 올바르지 않습니다.");
                }
            }
            if(true == check){
                // 권한 조회
                HashMap<String, Object> authCheckParamMap = new HashMap<String, Object>();
                authCheckParamMap.put("menuClass",paramMap.get("menuClass"));
                authCheckParamMap.put("muAuthId",paramMap.get("menuClassAuthId"));
                List<Map<String, Object>> authMenuRelationlistMap = webAuthMenuRelationSqlMapDAO.selectAuthMenuRelation(authCheckParamMap);
                int authMenuRelationlistMapSize = authMenuRelationlistMap.size();

                if(1==authMenuRelationlistMapSize){

                    if(("Y").equals(authMenuRelationlistMap.get(0).get("insertUseYn"))) {
                    }
                    else {
                        check = false;
                        map.put("msgCode", Constants.FAIL);
                        map.put("msgDesc", "등록 권한 정보가 없습니다.");
                    }
                }
                else {
                    check = false;
                    map.put("msgCode", Constants.FAIL);
                    map.put("msgDesc", "권한 정보가 없습니다.");
                }
            }

            if(true == check){
                paramMap.put("tDate", tDate);
                paramMap.put("tId", tId);
                paramMap.put("muMemberId", paramMap.get("loginMemberId"));

                String muPaymentRequestHistoryId = ("PRH").concat(String.valueOf(System.currentTimeMillis()));
                paramMap.put("muPaymentRequestHistoryId", muPaymentRequestHistoryId);
                webPaymentSqlMapDAO.insertPaymentRequestHistory(paramMap);

                log.debug("muPaymentRequestHistoryId :"+paramMap.get("muPaymentRequestHistoryId"));
                paramMap.put("muPaymentRequestHistoryId", paramMap.get("id"));
                map.put("muPaymentRequestHistoryId", paramMap.get("id"));

                map.put("msgCode", Constants.OK);
                map.put("msgDesc", "등록되었습니다.");
            }
        }
        catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
        log.debug("WebPaymentServiceImpl insertPaymentRequestHistory END");
        return map;
    }
    /**
     * 단말 결제응답 정보 등록
     *
     * @param paramMap
     * @return
     * @throws Exception
     */
    @Override
    @Transactional(rollbackFor={Exception.class}, propagation = Propagation.REQUIRES_NEW)
    public HashMap<String, Object> insertPaymentResponseHistory(
            HashMap<String, Object> paramMap) throws Exception{
        log.debug("WebPaymentServiceImpl insertPaymentResponseHistory START");

        HashMap<String, Object> map = new HashMap<String, Object>();

        log.debug("loginMemberId       :"+paramMap.get("loginMemberId"));

        log.debug("menuClass           :"+paramMap.get("menuClass"));

        log.debug("treatmentName       :"+paramMap.get("treatmentName"));

        try{
            boolean check  = true;
            String tId = String.valueOf(System.currentTimeMillis());
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Calendar c1 = Calendar.getInstance();
            String tDate = sdf.format(c1.getTime());

            if(true == check){
                // 사용자 확인
                List<Map<String, Object>> userListMap = webMemberSqlMapDAO.checkMember(paramMap);
                int userListMapSize = userListMap.size();

                if(1==userListMapSize){
                    paramMap.put("menuClassAuthId", userListMap.get(0).get("muAuthId"));
                }
                else {
                    check = false;
                    map.put("msgCode", Constants.FAIL);
                    map.put("msgDesc", "사용자 정보가 올바르지 않습니다.");
                }
            }
            if(true == check){
                // 권한 조회
                HashMap<String, Object> authCheckParamMap = new HashMap<String, Object>();
                authCheckParamMap.put("menuClass",paramMap.get("menuClass"));
                authCheckParamMap.put("muAuthId",paramMap.get("menuClassAuthId"));
                List<Map<String, Object>> authMenuRelationListMap = webAuthMenuRelationSqlMapDAO.selectAuthMenuRelation(authCheckParamMap);
                int authMenuRelationListMapSize = authMenuRelationListMap.size();

                if(1==authMenuRelationListMapSize){

                    if(("Y").equals(authMenuRelationListMap.get(0).get("insertUseYn"))) {
                    }
                    else {
                        check = false;
                        map.put("msgCode", Constants.FAIL);
                        map.put("msgDesc", "등록 권한 정보가 없습니다.");
                    }
                }
                else {
                    check = false;
                    map.put("msgCode", Constants.FAIL);
                    map.put("msgDesc", "권한 정보가 없습니다.");
                }
            }

            if(true == check){
                paramMap.put("tDate", tDate);
                paramMap.put("tId", tId);
                paramMap.put("muMemberId", paramMap.get("loginMemberId"));

                String muPaymentResponseHistoryId = ("PRH").concat(String.valueOf(System.currentTimeMillis()));
                paramMap.put("muPaymentResponseHistoryId", muPaymentResponseHistoryId);
                webPaymentSqlMapDAO.insertPaymentResponseHistory(paramMap);

                log.debug("muPaymentResponseHistoryId :"+paramMap.get("muPaymentResponseHistoryId"));
                paramMap.put("muPaymentResponseHistoryId", paramMap.get("id"));
                map.put("muPaymentResponseHistoryId", paramMap.get("id"));

                map.put("msgCode", Constants.OK);
                map.put("msgDesc", "등록되었습니다.");
            }
        }
        catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
        log.debug("WebPaymentServiceImpl insertPaymentResponseHistory END");
        return map;
    }
    /**
     * 결제 취소 정보 등록
     *
     * @param paramMap
     * @return
     * @throws Exception
     */
    @Override
    @Transactional(rollbackFor={Exception.class}, propagation = Propagation.REQUIRES_NEW)
    public HashMap<String, Object> paymentCancellation(
            HashMap<String, Object> paramMap) throws Exception{
        log.debug("WebPaymentServiceImpl paymentCancellation START");

        HashMap<String, Object> map = new HashMap<String, Object>();

        log.debug("loginMemberId       :"+paramMap.get("loginMemberId"));

        log.debug("menuClass           :"+paramMap.get("menuClass"));

        log.debug("muUserId            :"+paramMap.get("muUserId"));

        log.debug("paymentNumber       :"+paramMap.get("paymentNumber"));

        try{
            boolean check  = true;
            String tId = String.valueOf(System.currentTimeMillis());
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Calendar c1 = Calendar.getInstance();
            String tDate = sdf.format(c1.getTime());

            if(true == check){
                // 사용자 확인
                List<Map<String, Object>> userListMap = webMemberSqlMapDAO.checkMember(paramMap);
                int userListMapSize = userListMap.size();

                if(1==userListMapSize){
                    paramMap.put("menuClassAuthId", userListMap.get(0).get("muAuthId"));
                }
                else {
                    check = false;
                    map.put("msgCode", Constants.FAIL);
                    map.put("msgDesc", "사용자 정보가 올바르지 않습니다.");
                }
            }

            if(true == check){
                // 권한 조회
                HashMap<String, Object> authCheckParamMap = new HashMap<String, Object>();
                authCheckParamMap.put("menuClass",paramMap.get("menuClass"));
                authCheckParamMap.put("muAuthId",paramMap.get("menuClassAuthId"));
                List<Map<String, Object>> authMenuRelationlistMap = webAuthMenuRelationSqlMapDAO.selectAuthMenuRelation(authCheckParamMap);
                int authMenuRelationlistMapSize = authMenuRelationlistMap.size();

                if(1==authMenuRelationlistMapSize){

                    if(("Y").equals(authMenuRelationlistMap.get(0).get("insertUseYn"))) {

                    }
                    else {
                        check = false;
                        map.put("msgCode", Constants.FAIL);
                        map.put("msgDesc", "등록 권한 정보가 없습니다.");
                    }
                }
                else {
                    check = false;
                    map.put("msgCode", Constants.FAIL);
                    map.put("msgDesc", "권한 정보가 없습니다.");
                }
            }

            // 환불 및 취소인지 확인
            if(true == check){
                List<Map<String, Object>> listMap = webPaymentSqlMapDAO.selectPaymentPaymentNumber(paramMap);
                int listMapSize = listMap.size();

                if(0<listMapSize){
                    String cancelYn = String.valueOf(listMap.get(0).get("cancelYn"));

                    if(("N").equals(cancelYn)){
                        check = false;
                        map.put("msgCode", Constants.FAIL);
                        map.put("msgDesc", "결제취소 및 환불된 건입니다.");
                    }
                }
            }

            if(true == check) {
                paramMap.put("tDate", tDate);
                paramMap.put("tId", tId);
                paramMap.put("muMemberId", paramMap.get("loginMemberId"));

                //payment 정보 가져오기
                JSONParser jsonParser = new JSONParser();
                JSONArray jsonArray = (JSONArray) jsonParser.parse(String.valueOf(paramMap.get("paymentDataArray")));

                for (Object object : jsonArray) {
                    JSONObject jsonObject = (JSONObject) object;
                    HashMap<String, Object> dataMap = new HashMap<String, Object>();

                    dataMap.put("muUserId", paramMap.get("muUserId"));
                    dataMap.put("muPaymentId", jsonObject.get("muPaymentId"));

                    List<Map<String, Object>> paymentData = webPaymentSqlMapDAO.selectPayment(dataMap);

//                    HashMap<String, Object> idMap = new HashMap<>();
//                    HashMap<String, Object> newIdMap = new HashMap<>();

                    //수납 정보 등록
//                    for (int i = 0; i < paymentData.size(); i++) {

                    HashMap<String, Object> dataMap2 = new HashMap<>();
                    String muPaymentId = ("PMT").concat(String.valueOf(System.currentTimeMillis()));
                    dataMap2.put("muPaymentId", muPaymentId);
                    dataMap2.put("muUserId", paymentData.get(0).get("muUserId"));
                    dataMap2.put("paymentApprovalId", jsonObject.get("paymentApprovalId"));
                    dataMap2.put("paymentNumber", paymentData.get(0).get("paymentNumber"));
                    dataMap2.put("paymentCategoryItemId", paymentData.get(0).get("paymentCategoryItemId"));
                    dataMap2.put("paymentCategoryItemName", paymentData.get(0).get("paymentCategoryItemName"));
                    dataMap2.put("paymentCardInfo", paymentData.get(0).get("paymentCardInfo"));
                    dataMap2.put("cardInstallments", paymentData.get(0).get("cardInstallments"));
                    dataMap2.put("muMemberId", paramMap.get("muMemberId"));
                    dataMap2.put("muPaymentRequestHistoryId",jsonObject.get("muPaymentRequestHistoryId"));
                    dataMap2.put("muPaymentResponseHistoryId",jsonObject.get("muPaymentResponseHistoryId"));

                    if (Integer.parseInt("" + paymentData.get(0).get("amount")) < 0) {
                        dataMap2.put("amount", Math.abs(Integer.parseInt("" + paymentData.get(0).get("amount"))));
                    } else {
                        dataMap2.put("amount", Integer.parseInt("-" + paymentData.get(0).get("amount")));
                    }

                    if (Integer.parseInt("" + paymentData.get(0).get("vat")) < 0) {
                        dataMap2.put("vat", Math.abs(Integer.parseInt("" + paymentData.get(0).get("vat"))));
                    } else {
                        dataMap2.put("vat", Integer.parseInt("-" + paymentData.get(0).get("vat")));
                    }

                    if (Integer.parseInt("" + paymentData.get(0).get("paymentAmount")) < 0) {
                        dataMap2.put("refundAmount", Math.abs(Integer.parseInt("" + paymentData.get(0).get("paymentAmount"))));
                    } else {
                        dataMap2.put("refundAmount", Integer.parseInt("-" + paymentData.get(0).get("paymentAmount")));
                    }

                    dataMap2.put("status", "C");
                    dataMap2.put("modId", paramMap.get("modId"));
                    dataMap2.put("regId", paramMap.get("modId"));
                    dataMap2.put("tId", paramMap.get("tId"));
                    dataMap2.put("tDate", paramMap.get("tDate"));
                    webPaymentSqlMapDAO.insertPayment(dataMap2);

//                        idMap.put("muPaymentId" + i, paymentData.get(0).get("muPaymentId"));
//                        newIdMap.put("muPaymentId" + i, dataMap.get("id"));
//                    }

                    int membershipAmount = 0;
                    //수납 상세정보 등록
//                    for (int i = 0; i < newIdMap.size(); i++) {
                    HashMap<String, Object> dataMap3 = new HashMap<>();
                    List<Map<String, Object>> paymentDetailData = webPaymentSqlMapDAO.selectPaymentDetail((String) paymentData.get(0).get("muPaymentId"));

                    for (int j = 0; j < paymentDetailData.size(); j++) {
                        String muPaymentDetailId = ("PMD").concat(String.valueOf(System.currentTimeMillis()));

                        dataMap3.put("muPaymentDetailId", muPaymentDetailId);
                        dataMap3.put("muPaymentId", dataMap2.get("id"));
                        dataMap3.put("paymentNumber", paymentDetailData.get(j).get("paymentNumber"));
                        dataMap3.put("muReserveId", paymentDetailData.get(j).get("muReserveId"));
                        dataMap3.put("muTreatmentId", paymentDetailData.get(j).get("muTreatmentId"));
                        dataMap3.put("treatmentName", paymentDetailData.get(j).get("treatmentName"));
                        dataMap3.put("treatmentProcedureName", paymentDetailData.get(j).get("treatmentProcedureName"));
                        dataMap3.put("muTreatmentProcedureId", paymentDetailData.get(j).get("muTreatmentProcedureId"));
                        dataMap3.put("reserveMemberId", paymentDetailData.get(j).get("reserveMemberId"));
                        dataMap3.put("muMemberId", paramMap.get("muMemberId"));

                        if (Integer.parseInt("" + paymentDetailData.get(j).get("amount")) < 0) {
                            dataMap3.put("amount", Math.abs(Integer.parseInt("" + paymentDetailData.get(j).get("amount"))));
                        } else {
                            dataMap3.put("amount", Integer.parseInt("-" + paymentDetailData.get(j).get("amount")));
                        }

                        if (Integer.parseInt("" + paymentDetailData.get(j).get("vat")) < 0) {
                            dataMap3.put("vat", Math.abs(Integer.parseInt("" + paymentDetailData.get(j).get("vat"))));
                        } else {
                            dataMap3.put("vat", Integer.parseInt("-" + paymentDetailData.get(j).get("vat")));
                        }

                        if (paymentDetailData.get(j).get("membershipPrice") != null) {
                            dataMap3.put("membershipPrice", Math.abs(Integer.parseInt("" + paymentDetailData.get(j).get("membershipPrice"))));
                        }

                        if (Integer.parseInt("" + paymentDetailData.get(j).get("totalAmount")) < 0) {
                            dataMap3.put("totalAmount", Math.abs(Integer.parseInt("" + paymentDetailData.get(j).get("totalAmount"))));
                        } else {
                            dataMap3.put("totalAmount", Integer.parseInt("-" + paymentDetailData.get(j).get("totalAmount")));
                        }

                        dataMap3.put("modId", paramMap.get("modId"));
                        dataMap3.put("regId", paramMap.get("modId"));
                        dataMap3.put("tId", paramMap.get("tId"));
                        dataMap3.put("tDate", paramMap.get("tDate"));

                        webPaymentSqlMapDAO.insertPaymentDetail(dataMap3);

                        map.put("muPaymentDetailId", paramMap.get("id"));

                        if (paymentDetailData.get(j).get("membershipPrice") != null
                            && Integer.parseInt(String.valueOf(paymentDetailData.get(j).get("membershipPrice"))) < 0) {

                            HashMap<String, Object> dataMap5 = new HashMap<>();

                            String muMembershipHistoryId = ("M").concat(String.valueOf(System.currentTimeMillis()));
                            dataMap5.put("muMembershipHistoryId", muMembershipHistoryId);
                            dataMap5.put("muUserId", paramMap.get("muUserId"));
                            dataMap5.put("muMemberId", paramMap.get("muMemberId"));
                            dataMap5.put("muTreatmentId", paymentDetailData.get(j).get("muTreatmentId"));
                            dataMap5.put("muTreatmentProcedureId", paymentDetailData.get(j).get("muTreatmentProcedureId"));
                            dataMap5.put("rechargeAmount", Math.abs(Integer.parseInt(String.valueOf(paymentDetailData.get(j).get("membershipPrice")))));
                            dataMap5.put("reserveMemberId", paymentDetailData.get(j).get("reserveMemberId"));
                            dataMap5.put("regId", paramMap.get("regId"));
                            dataMap5.put("modId", paramMap.get("modId"));
                            dataMap5.put("tId", paramMap.get("tId"));
                            dataMap5.put("usageType", "D");
                            webMembershipSqlMapDAO.insertMembershipHistory(dataMap5);
                            membershipAmount += Math.abs(Integer.parseInt("" + paymentDetailData.get(j).get("membershipPrice")));
                        }
                    }
//                    }
                    //예약 테이블 업데이트
                    List<Map<String, Object>> reserveDataList = webPaymentSqlMapDAO.selectReserveId((String) jsonObject.get("muPaymentId"));
                    for (int i = 0; i < reserveDataList.size(); i++) {
                        HashMap<String, Object> dataMap4 = new HashMap<>();

                        dataMap4.put("muReserveId", reserveDataList.get(i).get("muReserveId"));
                        dataMap4.put("status", "C");
                        dataMap4.put("modId", paramMap.get("modId"));
                        webReserveSqlMapDAO.updateReserveStatus2(dataMap4);
                    }

                    if (membershipAmount > 0) {
                        //결제수단 멤버십이라면 멤버십 복구.
                        List<Map<String, Object>> membershipInfoList = webMembershipSqlMapDAO.selectTotalMembershipHistoryInfo(paramMap);

                        int membershipBalance = Integer.parseInt(((String) membershipInfoList.getFirst().get("membershipBalance")).replace(",", ""));

                        HashMap<String, Object> dataMap4 = new HashMap<>();

                        dataMap4.put("membershipBalance", membershipBalance + membershipAmount);
                        dataMap4.put("lastRechargeDate", sdf.format(c1.getTime()));
                        dataMap4.put("modId", paramMap.get("modId"));
                        dataMap4.put("tId", paramMap.get("tId"));
                        dataMap4.put("muUserId", paramMap.get("muUserId"));

                        webMembershipSqlMapDAO.updateMembership(dataMap4);
                    }

                    log.debug("muPaymentId :" + paramMap.get("muPaymentId"));
                    paramMap.put("muPaymentId", paramMap.get("muPaymentId"));
                    map.put("muPaymentId", paramMap.get("muPaymentId"));

                    map.put("msgCode", Constants.OK);
                    map.put("msgDesc", "결제 취소되었습니다.");
                }
            }
        }
        catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
        log.debug("WebPaymentServiceImpl paymentCancellation END");
        return map;
    }
    /**
     * 결제 취소 정보 등록 (취소 재결제)
     *
     * @param paramMap
     * @return
     * @throws Exception
     */
    @Override
    @Transactional(rollbackFor={Exception.class}, propagation = Propagation.REQUIRES_NEW)
    public HashMap<String, Object> paymentCancellationPay(
            HashMap<String, Object> paramMap) throws Exception{
        log.debug("WebPaymentServiceImpl paymentCancellationPay START");

        HashMap<String, Object> map = new HashMap<String, Object>();

        log.debug("loginMemberId       :"+paramMap.get("loginMemberId"));

        log.debug("menuClass           :"+paramMap.get("menuClass"));

        log.debug("muUserId            :"+paramMap.get("muUserId"));

        log.debug("paymentNumber       :"+paramMap.get("paymentNumber"));

        try{
            boolean check  = true;
            String tId = String.valueOf(System.currentTimeMillis());
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Calendar c1 = Calendar.getInstance();
            String tDate = sdf.format(c1.getTime());

            if(true == check){
                // 사용자 확인
                List<Map<String, Object>> userListMap = webMemberSqlMapDAO.checkMember(paramMap);
                int userListMapSize = userListMap.size();

                if(1==userListMapSize){
                    paramMap.put("menuClassAuthId", userListMap.get(0).get("muAuthId"));
                }
                else {
                    check = false;
                    map.put("msgCode", Constants.FAIL);
                    map.put("msgDesc", "사용자 정보가 올바르지 않습니다.");
                }
            }

            if(true == check){
                // 권한 조회
                HashMap<String, Object> authCheckParamMap = new HashMap<String, Object>();
                authCheckParamMap.put("menuClass",paramMap.get("menuClass"));
                authCheckParamMap.put("muAuthId",paramMap.get("menuClassAuthId"));
                List<Map<String, Object>> authMenuRelationlistMap = webAuthMenuRelationSqlMapDAO.selectAuthMenuRelation(authCheckParamMap);
                int authMenuRelationlistMapSize = authMenuRelationlistMap.size();

                if(1==authMenuRelationlistMapSize){

                    if(("Y").equals(authMenuRelationlistMap.get(0).get("insertUseYn"))) {

                    }
                    else {
                        check = false;
                        map.put("msgCode", Constants.FAIL);
                        map.put("msgDesc", "등록 권한 정보가 없습니다.");
                    }
                }
                else {
                    check = false;
                    map.put("msgCode", Constants.FAIL);
                    map.put("msgDesc", "권한 정보가 없습니다.");
                }
            }

            // 환불 및 취소인지 확인
            if(true == check){
                List<Map<String, Object>> listMap = webPaymentSqlMapDAO.selectPaymentPaymentNumber(paramMap);
                int listMapSize = listMap.size();

                if(0<listMapSize){
                    String cancelYn = String.valueOf(listMap.get(0).get("cancelYn"));

                    if(("N").equals(cancelYn)){
                        check = false;
                        map.put("msgCode", Constants.FAIL);
                        map.put("msgDesc", "결제취소 및 환불된 건입니다.");
                    }
                }
            }

            if(true == check) {
                paramMap.put("tDate", tDate);
                paramMap.put("tId", tId);
                paramMap.put("muMemberId", paramMap.get("loginMemberId"));

                //payment 정보 가져오기
                JSONParser jsonParser = new JSONParser();
                JSONArray jsonArray = (JSONArray) jsonParser.parse(String.valueOf(paramMap.get("paymentDataArray")));

                for (Object object : jsonArray) {
                    JSONObject jsonObject = (JSONObject) object;
                    HashMap<String, Object> dataMap = new HashMap<String, Object>();

                    dataMap.put("muUserId", paramMap.get("muUserId"));
                    dataMap.put("muPaymentId", jsonObject.get("muPaymentId"));

                    List<Map<String, Object>> paymentData = webPaymentSqlMapDAO.selectPayment(dataMap);

                    HashMap<String, Object> dataMap2 = new HashMap<>();
                    String muPaymentId = ("PMT").concat(String.valueOf(System.currentTimeMillis()));
                    dataMap2.put("muPaymentId", muPaymentId);
                    dataMap2.put("muUserId", paymentData.get(0).get("muUserId"));
                    dataMap2.put("paymentApprovalId", jsonObject.get("paymentApprovalId"));
                    dataMap2.put("paymentNumber", paymentData.get(0).get("paymentNumber"));
                    dataMap2.put("paymentCategoryItemId", paymentData.get(0).get("paymentCategoryItemId"));
                    dataMap2.put("paymentCategoryItemName", paymentData.get(0).get("paymentCategoryItemName"));
                    dataMap2.put("paymentCardInfo", paymentData.get(0).get("paymentCardInfo"));
                    dataMap2.put("cardInstallments", paymentData.get(0).get("cardInstallments"));
                    dataMap2.put("muMemberId", paramMap.get("muMemberId"));
                    dataMap2.put("muPaymentRequestHistoryId",jsonObject.get("muPaymentRequestHistoryId"));
                    dataMap2.put("muPaymentResponseHistoryId",jsonObject.get("muPaymentResponseHistoryId"));

                    if (Integer.parseInt("" + paymentData.get(0).get("amount")) < 0) {
                        dataMap2.put("amount", Math.abs(Integer.parseInt("" + paymentData.get(0).get("amount"))));
                    } else {
                        dataMap2.put("amount", Integer.parseInt("-" + paymentData.get(0).get("amount")));
                    }

                    if (Integer.parseInt("" + paymentData.get(0).get("vat")) < 0) {
                        dataMap2.put("vat", Math.abs(Integer.parseInt("" + paymentData.get(0).get("vat"))));
                    } else {
                        dataMap2.put("vat", Integer.parseInt("-" + paymentData.get(0).get("vat")));
                    }

                    if (Integer.parseInt("" + paymentData.get(0).get("paymentAmount")) < 0) {
                        dataMap2.put("refundAmount", Math.abs(Integer.parseInt("" + paymentData.get(0).get("paymentAmount"))));
                    } else {
                        dataMap2.put("refundAmount", Integer.parseInt("-" + paymentData.get(0).get("paymentAmount")));
                    }

                    dataMap2.put("status", "CN");
                    dataMap2.put("modId", paramMap.get("modId"));
                    dataMap2.put("regId", paramMap.get("modId"));
                    dataMap2.put("tId", paramMap.get("tId"));
                    dataMap2.put("tDate", paramMap.get("tDate"));
                    webPaymentSqlMapDAO.insertPayment(dataMap2);


                    int membershipAmount = 0;
                    //수납 상세정보 등록
                    HashMap<String, Object> dataMap3 = new HashMap<>();
                    List<Map<String, Object>> paymentDetailData = webPaymentSqlMapDAO.selectPaymentDetail((String) paymentData.get(0).get("muPaymentId"));

                    for (int j = 0; j < paymentDetailData.size(); j++) {
                        String muPaymentDetailId = ("PMD").concat(String.valueOf(System.currentTimeMillis()));

                        dataMap3.put("muPaymentDetailId", muPaymentDetailId);
                        dataMap3.put("muPaymentId", dataMap2.get("id"));
                        dataMap3.put("paymentNumber", paymentDetailData.get(j).get("paymentNumber"));
                        dataMap3.put("muReserveId", paymentDetailData.get(j).get("muReserveId"));
                        dataMap3.put("muTreatmentId", paymentDetailData.get(j).get("muTreatmentId"));
                        dataMap3.put("treatmentName", paymentDetailData.get(j).get("treatmentName"));
                        dataMap3.put("treatmentProcedureName", paymentDetailData.get(j).get("treatmentProcedureName"));
                        dataMap3.put("muTreatmentProcedureId", paymentDetailData.get(j).get("muTreatmentProcedureId"));
                        dataMap3.put("reserveMemberId", paymentDetailData.get(j).get("reserveMemberId"));
                        dataMap3.put("muMemberId", paramMap.get("muMemberId"));

                        if (Integer.parseInt("" + paymentDetailData.get(j).get("amount")) < 0) {
                            dataMap3.put("amount", Math.abs(Integer.parseInt("" + paymentDetailData.get(j).get("amount"))));
                        } else {
                            dataMap3.put("amount", Integer.parseInt("-" + paymentDetailData.get(j).get("amount")));
                        }

                        if (Integer.parseInt("" + paymentDetailData.get(j).get("vat")) < 0) {
                            dataMap3.put("vat", Math.abs(Integer.parseInt("" + paymentDetailData.get(j).get("vat"))));
                        } else {
                            dataMap3.put("vat", Integer.parseInt("-" + paymentDetailData.get(j).get("vat")));
                        }

                        if (paymentDetailData.get(j).get("membershipPrice") != null) {
                            dataMap3.put("membershipPrice", Math.abs(Integer.parseInt("" + paymentDetailData.get(j).get("membershipPrice"))));
                        }

                        if (Integer.parseInt("" + paymentDetailData.get(j).get("totalAmount")) < 0) {
                            dataMap3.put("totalAmount", Math.abs(Integer.parseInt("" + paymentDetailData.get(j).get("totalAmount"))));
                        } else {
                            dataMap3.put("totalAmount", Integer.parseInt("-" + paymentDetailData.get(j).get("totalAmount")));
                        }

                        dataMap3.put("modId", paramMap.get("modId"));
                        dataMap3.put("regId", paramMap.get("modId"));
                        dataMap3.put("tId", paramMap.get("tId"));
                        dataMap3.put("tDate", paramMap.get("tDate"));

                        webPaymentSqlMapDAO.insertPaymentDetail(dataMap3);

                        map.put("muPaymentDetailId", paramMap.get("id"));

                        if (paymentDetailData.get(j).get("membershipPrice") != null
                            && Integer.parseInt(String.valueOf(paymentDetailData.get(j).get("membershipPrice"))) < 0) {

                            HashMap<String, Object> dataMap5 = new HashMap<>();

                            String muMembershipHistoryId = ("M").concat(String.valueOf(System.currentTimeMillis()));
                            dataMap5.put("muMembershipHistoryId", muMembershipHistoryId);
                            dataMap5.put("muUserId", paramMap.get("muUserId"));
                            dataMap5.put("muMemberId", paramMap.get("muMemberId"));
                            dataMap5.put("muTreatmentId", paymentDetailData.get(j).get("muTreatmentId"));
                            dataMap5.put("muTreatmentProcedureId", paymentDetailData.get(j).get("muTreatmentProcedureId"));
                            dataMap5.put("rechargeAmount", Math.abs(Integer.parseInt(String.valueOf(paymentDetailData.get(j).get("membershipPrice")))));
                            dataMap5.put("reserveMemberId", paymentDetailData.get(j).get("reserveMemberId"));
                            dataMap5.put("regId", paramMap.get("regId"));
                            dataMap5.put("modId", paramMap.get("modId"));
                            dataMap5.put("tId", paramMap.get("tId"));
                            dataMap5.put("usageType", "D");
                            webMembershipSqlMapDAO.insertMembershipHistory(dataMap5);
                            membershipAmount += Math.abs(Integer.parseInt("" + paymentDetailData.get(j).get("membershipPrice")));
                        }
                    }

                    //예약 테이블 업데이트
                    List<Map<String, Object>> reserveDataList = webPaymentSqlMapDAO.selectReserveId((String) jsonObject.get("muPaymentId"));
                    for (int i = 0; i < reserveDataList.size(); i++) {
                        HashMap<String, Object> dataMap4 = new HashMap<>();

                        dataMap4.put("muReserveId", reserveDataList.get(i).get("muReserveId"));
                        dataMap4.put("status", "CN");
                        dataMap4.put("modId", paramMap.get("modId"));
                        webReserveSqlMapDAO.updateReserveStatus2(dataMap4);
                    }

                    if (membershipAmount > 0) {
                        //결제수단 멤버십이라면 멤버십 복구.
                        List<Map<String, Object>> membershipInfoList = webMembershipSqlMapDAO.selectTotalMembershipHistoryInfo(paramMap);

                        int membershipBalance = Integer.parseInt(((String) membershipInfoList.getFirst().get("membershipBalance")).replace(",", ""));

                        HashMap<String, Object> dataMap4 = new HashMap<>();

                        dataMap4.put("membershipBalance", membershipBalance + membershipAmount);
                        dataMap4.put("lastRechargeDate", sdf.format(c1.getTime()));
                        dataMap4.put("modId", paramMap.get("modId"));
                        dataMap4.put("tId", paramMap.get("tId"));
                        dataMap4.put("muUserId", paramMap.get("muUserId"));

                        webMembershipSqlMapDAO.updateMembership(dataMap4);
                    }

                    log.debug("muPaymentId :" + paramMap.get("muPaymentId"));
                    paramMap.put("muPaymentId", paramMap.get("muPaymentId"));
                    map.put("muPaymentId", paramMap.get("muPaymentId"));

                    map.put("msgCode", Constants.OK);
                    map.put("msgDesc", "결제 취소되었습니다.");
                }
            }
        }
        catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
        log.debug("WebPaymentServiceImpl paymentCancellationPay END");
        return map;
    }

    private int getIntFromJson(JSONObject jsonObject, String key) {
        if(jsonObject.get(key)!=null) {
            return Integer.parseInt(String.valueOf(jsonObject.get(key)));
        }else{
            return 0;
        }
    }
    private void populateCommonData(HashMap<String, Object> dataMap, Map<String, Object> paramMap, JSONObject jsonObject) {
        dataMap.put("muPaymentId", paramMap.get("muPaymentId"));
        dataMap.put("paymentNumber", paramMap.get("paymentNumber"));
        dataMap.put("muReserveId", jsonObject.get("muReserveId"));
        dataMap.put("muTreatmentId", jsonObject.get("muTreatmentId"));
        dataMap.put("treatmentName", jsonObject.get("treatmentName"));
        dataMap.put("treatmentProcedureName", jsonObject.get("treatmentProcedureName"));
        dataMap.put("muTreatmentProcedureId", jsonObject.get("muTreatmentProcedureId"));
        dataMap.put("reserveMemberId", jsonObject.get("reserveMemberId"));
        dataMap.put("muMemberId", paramMap.get("muMemberId"));
        dataMap.put("modId", paramMap.get("modId"));
        dataMap.put("regId", paramMap.get("modId"));
        dataMap.put("tId", paramMap.get("tId"));
        dataMap.put("tDate", paramMap.get("tDate"));
    }

    private void insertPaymentDetail(HashMap<String, Object> dataMap, Map<String, Object> paramMap, JSONObject jsonObject, boolean zeroAmount) throws ParseException {

        String paymentData          = String.valueOf(paramMap.get("paymentData"));
        JSONParser parser = new JSONParser();
        String status = "";

        if(true == ValidationCheckUtil.emptyCheck(paymentData)) {
            Object paymentObj = parser.parse( paymentData );
            JSONArray paymentDataObj = (JSONArray) paymentObj;
            JSONObject paymentObject = (JSONObject) paymentDataObj.get(0);
            status = (String)paymentObject.get("status");
        }

        int amount = getIntFromJson(jsonObject, "amount");
        int vat = getIntFromJson(jsonObject, "vat");
        int totalAmount = getIntFromJson(jsonObject, "totalAmount");
        int discountPrice = getIntFromJson(jsonObject, "discountPrice");
        int membershipPrice = getIntFromJson(jsonObject, "membershipPrice");

        boolean isAmountZero = (amount == 0 && vat == 0 && totalAmount == 0);
        boolean isDiscountAndMembershipZero = (discountPrice == 0 && membershipPrice == 0);

        if (isAmountZero && !status.equals("NP") && (zeroAmount || isDiscountAndMembershipZero)) {
            return;
        }

        populateCommonData(dataMap, paramMap, jsonObject);
        dataMap.put("amount",jsonObject.get("amount"));
        dataMap.put("vat",jsonObject.get("vat"));
        dataMap.put("totalAmount",jsonObject.get("totalAmount"));
        dataMap.put("discountPrice", zeroAmount ? 0 : jsonObject.get("discountPrice"));
        dataMap.put("membershipPrice", zeroAmount ? 0 : jsonObject.get("membershipPrice"));
        webPaymentSqlMapDAO.insertPaymentDetail(dataMap);
    }

    private void insertAdditionalPaymentDetail(HashMap<String, Object> dataMap, Map<String, Object> paramMap, JSONObject jsonObject) {
        int discountAmount = getIntFromJson(jsonObject, "discountAmount");
        int membershipPrice = getIntFromJson(jsonObject, "membershipPrice");
        if (0 == discountAmount && 0 == membershipPrice) {
            return;
        }
        dataMap.put("muPaymentDetailId", ("PMD").concat(String.valueOf(System.currentTimeMillis())));
        populateCommonData(dataMap, paramMap, jsonObject);
        dataMap.put("muPaymentId", paramMap.get("muPaymentId2"));
        dataMap.put("amount", 0);
        dataMap.put("vat", 0);
        dataMap.put("discountPrice", jsonObject.get("discountPrice"));
        dataMap.put("membershipPrice", jsonObject.get("membershipPrice"));
        dataMap.put("totalAmount", 0);
        webPaymentSqlMapDAO.insertPaymentDetail(dataMap);
    }
}
