package com.bb.admin.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Random;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.reactive.function.client.WebClient;

import com.bb.model.CommonParamAdmin;
import com.bb.model.PageFormVO;
import com.bb.model.Site;
import com.bb.model.SiteSearch;
import com.bb.model.Vendor;
import com.bb.service.CreditService;
import com.bb.service.SiteService;
import com.bb.util.PagingUtil;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;

import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;



@Slf4j
@Controller
@RequestMapping(value = "/agent")
@PreAuthorize("hasRole('ADMIN')")
public class AgentController {

    @Autowired
    SiteService siteService;

    @Autowired
    CreditService creditService;

    @Autowired
    private WebClient webClient; // 싱글톤 WebClient 주입
	/*
	 * 
	 * TPA 에이전트 목록 페이지 수정사항
		1. 에이전트 -> "에이전시" 로 용어수정 
		2. 에이전시 목록 수정사항 : 
		- 단계 = 레벨.
		- 번호 : 생성 순번 (컬럼 맨 앞으로)
		- 분류 : 두가지 타입 (추후 추가될수있음) NA(Normal Agency), IA(Insure Agency)
		              NA, IA
		- 타입 : Ota (Operator Agency) : 솔루션 운영하는 에이전시, Ppa (Paper Agency) : 하위 총판만 운영하는 에이전시
		3. 검색옵션 추가 : 분류, 타입 각각 따로 검색 가능하도록 분리
		4. 데이터 적용안되어 있는부분 적용 : 요율, 총 지급받은 금액 등
		    요율 : 기준요율만 적시 (벤더별 요율은 상세페이지에서 표시됨)
		5. 소속 에이전트 삭제(어차피 내 소속임) 에이전트 아이디 클릭시 상세페이지 이동
		6. 가입시각 -> 가입일시로 수정 , 가운데 "T" "%"문자 제거.
		7. 관리 컬럼은 유지 타이틀 이름도 관리 유자, 내용 관리 글자 제거. 
		   "정지"버튼 추가(클릭시 모든기능정지) "블랙"버튼 추가 (클릭시 로그인 및 PT충환전 중지) 
		    위 기능 구현하도록 작업
	 */


	@GetMapping("")
	public String list( HttpServletRequest request , ModelMap model, @ModelAttribute("searchVO") SiteSearch search) throws Exception {
		Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
		Site loginSite = (Site)authentication.getDetails();
		model.put("loginSite", loginSite);
		long siteCredit = siteService.getSiteCredit(loginSite.getSiteId());	    	
		long underSiteCredit = siteService.getUnderSiteCredit(loginSite.getSiteId());
		
		log.info("underSiteCredit" + underSiteCredit);
		
		model.put("siteCredit", siteCredit);	
		long sitePoint = siteService.getSitePoint(loginSite.getSiteId());
		model.put("sitePoint", sitePoint);	
		model.put("underSiteCredit", underSiteCredit);	    	
		HashMap creditWait = siteService.getCreditWait(loginSite.getSiteIdx());
		model.put("creditWait", creditWait);	  
		long insureAmt = siteService.getInsureAmt(loginSite.getSiteId());
		long insurePointAmt = siteService.getInsurePointAmt(loginSite.getSiteId());	
		model.put("insureAmt", insureAmt);	  
		model.put("insurePointAmt", insurePointAmt);	  
		 
		PageFormVO pageVo= new PageFormVO();	  
		
		if(loginSite.getSiteLevel() >0) {
			search.setUpperSiteId(loginSite.getSiteId());
		}
		
		int totalCount = siteService.getSiteListCnt(search);
		if (totalCount != 0) {
			PageFormVO commonForm = new PageFormVO();
			commonForm.setFunction_name("goPage");
			commonForm.setPage(search.getPage());
			commonForm.setCount_per_page(20);
			if(search.getCount_per_list()==0) {
				commonForm.setCount_per_list(10);
			} else {
				commonForm.setCount_per_list(search.getCount_per_list());
			}
			commonForm.setTatal_list_count(totalCount);
			pageVo = PagingUtil.setPageUtil(commonForm);
			search.setLimit(pageVo.getLimit());
			search.setOffset(pageVo.getOffset());
			search.setTatal_list_count(totalCount);
			
			model.put("pageInfo", pageVo.getPagination());
		}
		
		List<HashMap> siteList = siteService.getSiteList(search);
		model.put("siteList", siteList);
		
		return "admin/agent";        
	}
  
  
	@GetMapping("/detail/{siteIdx}")
	public String detail( HttpServletRequest request , ModelMap model, @ModelAttribute("searchVO") SiteSearch search) throws Exception {
		Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
		Site loginSite = (Site)authentication.getDetails();
		model.put("loginSite", loginSite);
		
		long siteCredit = siteService.getSiteCredit(loginSite.getSiteId());	    	
		long underSiteCredit = siteService.getUnderSiteCredit(loginSite.getSiteId());
		
		log.info("#-Agent::DETAIL::underSiteCredit" + underSiteCredit);
		
		model.put("siteCredit", siteCredit);	
		long sitePoint = siteService.getSitePoint(loginSite.getSiteId());
		model.put("sitePoint", sitePoint);	
		model.put("underSiteCredit", underSiteCredit);	    	
		HashMap creditWait = siteService.getCreditWait(loginSite.getSiteIdx());
		model.put("creditWait", creditWait);	  
		long insureAmt = siteService.getInsureAmt(loginSite.getSiteId());
		long insurePointAmt = siteService.getInsurePointAmt(loginSite.getSiteId());	
		model.put("insureAmt", insureAmt);	  
		model.put("insurePointAmt", insurePointAmt);	  
		
		log.info("#-Agent::DETAIL::siteIdx {}" , search.getSiteIdx());
		if(loginSite.getSiteLevel() >0) {
			search.setUpperSiteId(""+loginSite.getSiteId());
		}
		Site targetSite = siteService.getSiteDetail(search);
		model.put("targetSite", targetSite);
		
		model.put("uppersiteIdx", loginSite.getSiteIdx());
		
		List<HashMap> vederRateList = siteService.getVenderRateList(targetSite);
		model.put("vederRateList", vederRateList);
		log.info("#-Agent::DETAIL::vederRateList {}", vederRateList.size());
		log.info("#-Agent::DETAIL::vederRateList {}", vederRateList);
		
		/*
		HashMap vendorParam = new HashMap<>();
		vendorParam.put("siteIdx", search.getSiteIdx());
		vendorParam.put("vendor", "nexus");
		HashMap<String, String> nexusInfo = siteService.getSiteOnlyVendorInfo(vendorParam);
		log.info("#-Agent::DETAIL::nexusInfo::"+nexusInfo);
		model.put("nexusInfo", nexusInfo);
		
		vendorParam.put("vendor", "xtreem");
		HashMap<String, String> xtreemInfo = siteService.getSiteOnlyVendorInfo(vendorParam);
		log.info("#-Agent::DETAIL::xtreemInfo::"+xtreemInfo);
		model.put("xtreemInfo", xtreemInfo);
		*/
		
		HashMap parsEvoInfo = siteService.getParseUseYn(targetSite.getSiteIdx());
		int parsEvoAmount = (int) parsEvoInfo.get("parsEvoAmount");
		model.put("parsEvoAmount", parsEvoAmount);
		
		List<HashMap> mylist = siteService.getSiteVendorList2(targetSite.getSiteIdx());
    	List<HashMap> vendorlist = siteService.getVendorList2(targetSite.getSiteIdx());
    	model.put("mylist", mylist);
    	log.info("#-Agent::DETAIL::mylist::"+mylist);
    	model.put("vendorlist", vendorlist);
    	log.info("#-Agent::DETAIL::vendorlist::"+vendorlist);
    	
    	HashMap creditInfo = siteService.getSiteSubCredit(targetSite.getSiteId());
    	model.put("subCreditInfo", creditInfo);
		
		return "admin/popup";
	}
	
	@RequestMapping("/saveSvcr")
		public @ResponseBody JSONObject saveSvcr(HttpServletRequest request, ModelMap model, CommonParamAdmin commonParamAdmin) throws Exception {
			final String LOG_PREFIX = "#-SAVE_SCVR:::";
			log.info(LOG_PREFIX + "CommonParamAdmin: " + commonParamAdmin.toString());
			
			JSONObject obj = new JSONObject();
			ObjectMapper mapper = new ObjectMapper();
			HashMap paramMap = mapper.readValue(commonParamAdmin.getParam().toString(), new TypeReference<HashMap>() {});
			
			if(paramMap.get("vendorIdx") != null) {
				SiteSearch targetSearch = new SiteSearch();
				long targetSiteIdx = Long.parseLong(commonParamAdmin.getParam().get("targetSiteIdx").toString());
				targetSearch.setSiteIdx(targetSiteIdx);
				Site targetSite = siteService.getSiteDetail(targetSearch);
				
				String siteUrl = targetSite.getSiteCbUrl() + "/gameRateChange";
				paramMap.put("siteIdx", targetSiteIdx); 
				
				if(Integer.parseInt(paramMap.get("type").toString()) == 0) {
					siteService.saveVendorRate(paramMap);               
				}
				siteService.saveSvcr(paramMap, Integer.parseInt(paramMap.get("type").toString()));

				// 외부 API 호출 (WebClient 방식)
				if(Integer.parseInt(paramMap.get("type").toString()) == 0) {
					sendGameRateChange(siteUrl, paramMap);
				}           
			
				if(targetSite.getSiteLevel() < 1) {
					siteService.updateVendorUseYn(paramMap);
				}
			}
			obj.put("RES", "SUCCESS");
			return obj;
		}

@RequestMapping("/saveSvcrAll")
    public @ResponseBody JSONObject saveSvcrAll(HttpServletRequest request, ModelMap model, CommonParamAdmin commonParamAdmin) throws Exception {
        final String LOG_PREFIX = "#-SAVE_SCVRALL:::";
		log.info(LOG_PREFIX + "CommonParamAdmin: " + commonParamAdmin.toString());
		
        JSONObject obj = new JSONObject();

        for(int i=0; i < commonParamAdmin.getParamlist().length; i++) {
            JSONObject paramData = commonParamAdmin.getParamlist()[i];
            paramData.put("siteIdx", commonParamAdmin.getParam().get("targetSiteIdx"));
            ObjectMapper mapper = new ObjectMapper();
            HashMap paramMap = mapper.readValue(paramData.toString(), new TypeReference<HashMap>() {});
            
            long targetSiteIdx = Long.parseLong(commonParamAdmin.getParam().get("targetSiteIdx").toString());
            SiteSearch targetSearch = new SiteSearch();
            targetSearch.setSiteIdx(targetSiteIdx);
            Site targetSite = siteService.getSiteDetail(targetSearch);
            String siteUrl = targetSite.getSiteCbUrl() + "/gameRateChange";

            if(paramMap.get("vendorIdx") != null) {
                paramMap.put("siteIdx", targetSiteIdx); 
                if(Integer.parseInt(paramMap.get("type").toString()) == 0) {
                    siteService.saveVendorRate(paramMap);               
                }
                siteService.saveSvcr(paramMap, Integer.parseInt(paramMap.get("type").toString()));
            
                // 외부 API 호출 (WebClient 방식)
                if(Integer.parseInt(paramMap.get("type").toString()) == 0) {
                    sendGameRateChange(siteUrl, paramMap);
                }           
            
                if(targetSite.getSiteLevel() < 1) {
                    siteService.updateVendorUseYn(paramMap);
                }
            }
        }
        obj.put("RES", "SUCCESS");
        return obj;
    }
	
	/**
		 * WebClient를 이용한 외부 API 호출 공통 메서드 (동기 방식)
		 */
		private void sendGameRateChange(String url, HashMap paramMap) {
			try {
				log.info("##### WebClient gmeRateChange 시작 #####");
				
				JSONObject paramBody = new JSONObject();
				paramBody.put("siteApiKey", siteService.getSiteKey(paramMap));
				paramBody.put("vendor", siteService.getVendorTitle(paramMap));
				paramBody.put("vendorIdx", paramMap.get("vendorIdx"));
				paramBody.put("gameRate", Double.parseDouble(paramMap.get("rate").toString()));

				String response = webClient.post()
						.uri(url)
						.contentType(MediaType.APPLICATION_JSON)
						.accept(MediaType.APPLICATION_JSON)
						.header("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36")
						.bodyValue(paramBody.toString())
						.retrieve()
						.bodyToMono(String.class)
						.block(); // MVC 환경이므로 결과를 기다림(동기)

				log.info("##### WebClient 응답 완료 : {}", response);
			} catch (Exception e) {
				log.error("##### WebClient 호출 에러 : {}", e.getMessage());
			}
		}

	@GetMapping("/add")
	public String add( HttpServletRequest request , ModelMap model, @ModelAttribute("searchVO") SiteSearch search) throws Exception {
		Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
		Site loginSite = (Site)authentication.getDetails();
		model.put("loginSite", loginSite);
		long siteCredit = siteService.getSiteCredit(loginSite.getSiteId());	    	
		long underSiteCredit = siteService.getUnderSiteCredit(loginSite.getSiteId());
		
		log.info("underSiteCredit" + underSiteCredit);
		
		model.put("siteCredit", siteCredit);	
		long sitePoint = siteService.getSitePoint(loginSite.getSiteId());
		model.put("sitePoint", sitePoint);	
		model.put("underSiteCredit", underSiteCredit);	    	
		HashMap creditWait = siteService.getCreditWait(loginSite.getSiteIdx());
		model.put("creditWait", creditWait);	  
		long insureAmt = siteService.getInsureAmt(loginSite.getSiteId());
		long insurePointAmt = siteService.getInsurePointAmt(loginSite.getSiteId());	
		model.put("insureAmt", insureAmt);	  
		model.put("insurePointAmt", insurePointAmt);	  
		
		return "admin/agentAdd";
	}
  
  
	@RequestMapping("/siteUpdate")
	public @ResponseBody JSONObject siteUpdate( HttpServletRequest request, ModelMap model, Site site) throws Exception {
		JSONObject obj = new JSONObject();
		
		Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
		Site loginSite = (Site)authentication.getDetails();
		site.setUpperSiteId(loginSite.getSiteId());
		site.setUpperSiteIdx(loginSite.getSiteIdx());
		final String LOG_PREFIX = "#-super::siteUpdate:::";
		
		log.info(LOG_PREFIX+ "Site Info: " + site.toString());
		log.info(LOG_PREFIX+ "Site IP: " + site.getSiteIp());
		siteService.siteUpdate(LOG_PREFIX, site);
		
		obj.put("RES", "SUCCESS");
		
		return obj;
	}
	
	@RequestMapping("/agentUpdate")
	public @ResponseBody JSONObject  agentUpdate( HttpServletRequest request, ModelMap model, Site site) throws Exception {
		JSONObject obj = new JSONObject();  
		Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
		Site loginSite = (Site)authentication.getDetails();
		// site.setSiteId(loginSite.getSiteId());
		final String LOG_PREFIX = "#-super::agentUpdate:::";
	  
		if("new".equals(site.getSiteKey())) {
			String newsiteKey = makeApiKey(loginSite.getSiteId());
			site.setSiteKey(newsiteKey);
			obj.put("DATA", newsiteKey);
		}
		
		log.info(LOG_PREFIX+ "Site Info: " + site.toString());
		log.info(LOG_PREFIX+ "Site IP: " + site.getSiteIp());
		siteService.siteUpdate(LOG_PREFIX, site);
		obj.put("RES", "SUCCESS");
    	
	   return obj;
	}
	
	@RequestMapping("/agentIpsUpdate")
    public @ResponseBody JSONObject  agentIpsUpdate( HttpServletRequest request, ModelMap model,  Site site) throws Exception {
			JSONObject obj = new JSONObject();  
		Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
	   Site loginSite = (Site)authentication.getDetails();
	   // site.setSiteId(loginSite.getSiteId());
	    
	     
	    siteService.agentIpsUpdate(site)  ;
	   
	           
    	obj.put("RES", "SUCCESS");
   
    
		return obj;
    }

	@RequestMapping("/forDefault")
	public @ResponseBody JSONObject forDefault(HttpServletRequest request, ModelMap model, SiteSearch search) throws Exception {
		JSONObject obj = new JSONObject();
		
		//Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
		//Site site = (Site) authentication.getDetails();
		
		Site site = siteService.getSiteDetail(search);
		final String LOG_PREFIX = "#-Proc::forDefault::"+site.getSiteIdx()+"::";
		log.info(LOG_PREFIX + "loginSite::" + site.toString());
		log.info(LOG_PREFIX+ "Site IP: " + site.getSiteIp());
		
		siteService.siteUpdate(LOG_PREFIX, site);
		siteService.forDefaultProc(site);
		
		obj.put("RES", "SUCCESS");
		
		return obj;
	}
	
	@RequestMapping("/saveParsEvoAmount")
	public @ResponseBody JSONObject saveParsEvoAmount(HttpServletRequest request, ModelMap model, SiteSearch param) throws Exception {
		JSONObject obj = new JSONObject();
		final String LOG_PREFIX = "#-Proc::saveParsEvoAmount::"+param.getSiteIdx()+"::";
		log.info(LOG_PREFIX + "ParsEvoAmount::" + param.getParsEvoAmount());
		
		int updResult = siteService.saveParsEvoAmount(param);
		
		obj.put("RES", "SUCCESS");
		
		return obj;
	}
  
	@RequestMapping("/creditRateSave")
	public @ResponseBody JSONObject  setSave( HttpServletRequest request, ModelMap model,  CommonParamAdmin commonParamAdmin ) throws Exception {
		Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
		
		Site loginSite = (Site)authentication.getDetails();
		
		JSONObject obj = new JSONObject();
		log.info(commonParamAdmin.toString());
		
		for(int i=0;i<commonParamAdmin.getParamlist().length;i++) {
			JSONObject paramData = commonParamAdmin.getParamlist()[i];
			paramData.put("siteIdx", commonParamAdmin.getParam().get("targetSiteIdx"));
			paramData.put("insureUpSiteIdx", loginSite.getSiteIdx());
			log.info(paramData.toString());
			
			ObjectMapper mapper = new ObjectMapper();
			HashMap paramMap = mapper.readValue(paramData.toString(), new TypeReference<HashMap>() {});
			if(paramMap.get("vendorIdx")!=null) {
				siteService.saveVendorRate(paramMap);
				siteService.updateVendorUseYn(paramMap);
			}
		}
		
		obj.put("RES", "SUCCESS");
		
		return obj;
	}
  
  
	@RequestMapping("/insurePoinRateSave")
	public @ResponseBody JSONObject  insurePointRateSave( HttpServletRequest request, ModelMap model,  CommonParamAdmin commonParamAdmin ) throws Exception {
		Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
		
		Site loginSite = (Site)authentication.getDetails();
		
		JSONObject obj = new JSONObject();
		log.info(commonParamAdmin.toString());
		
		for(int i=0;i<commonParamAdmin.getParamlist().length;i++) {
			JSONObject paramData = commonParamAdmin.getParamlist()[i];
			paramData.put("siteIdx", commonParamAdmin.getParam().get("targetSiteIdx"));
			paramData.put("insureUpSiteIdX", loginSite.getSiteIdx());
			log.info(paramData.toString());
			
			ObjectMapper mapper = new ObjectMapper();
			HashMap paramMap = mapper.readValue(paramData.toString(), new TypeReference<HashMap>() {});
			siteService.saveVendorInsurePointRate(paramMap);
		}
		
		obj.put("RES", "SUCCESS");
		
		return obj;
	}


	@RequestMapping("/addProc")
	public @ResponseBody JSONObject addProc( HttpServletRequest request, ModelMap model,  Site site) throws Exception {
		Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
		
		Site loginSite = (Site)authentication.getDetails();
		site.setUpperSiteId(loginSite.getSiteId());
		site.setUpperSiteIdx(loginSite.getSiteIdx());
		site.setSiteKey(makeApiKey(site.getSiteId()));
		JSONObject obj = new JSONObject();
		
		if(site.getIsTransfer() == null || "".equals(site.getIsTransfer())) {
			site.setIsTransfer("N");
	    }
		
		log.info(site.toString());
		
		siteService.addProc(site);
		obj.put("RES", "SUCCESS");
		
		return obj;
	}


	@GetMapping("/transaction")
	public String transaction( HttpServletRequest request , ModelMap model , @ModelAttribute("searchVO") SiteSearch search) throws Exception {
		Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
		
		Site loginSite = (Site)authentication.getDetails();
		model.put("loginSite", loginSite);
		long siteCredit = siteService.getSiteCredit(loginSite.getSiteId());
		long underSiteCredit = siteService.getUnderSiteCredit(loginSite.getSiteId());
		long sitePoint = siteService.getSitePoint(loginSite.getSiteId());
		
		model.put("sitePoint", sitePoint);	
		model.put("siteCredit", siteCredit);	
		model.put("underSiteCredit", underSiteCredit);
		HashMap creditWait = siteService.getCreditWait(loginSite.getSiteIdx());
		
		model.put("creditWait", creditWait);	  
		long insureAmt = siteService.getInsureAmt(loginSite.getSiteId());
		long insurePointAmt = siteService.getInsurePointAmt(loginSite.getSiteId());	
		model.put("insureAmt", insureAmt);	  
		model.put("insurePointAmt", insurePointAmt);
		
		PageFormVO pageVo= new PageFormVO();	    	
		search.setSiteId(loginSite.getSiteId());
		search.setSiteIdx(loginSite.getSiteIdx());
		
		int totalCount = creditService.getSiteTranListCnt(search);
		if(totalCount != 0) {
			PageFormVO commonForm = new PageFormVO();
			commonForm.setFunction_name("goPage");
			commonForm.setPage(search.getPage());
			commonForm.setCount_per_page(20);
			if(search.getCount_per_list()==0) {
				commonForm.setCount_per_list(15);
			} else {
				commonForm.setCount_per_list(search.getCount_per_list());
			}
			commonForm.setTatal_list_count(totalCount);
			pageVo = PagingUtil.setPageUtil(commonForm);
			search.setLimit(pageVo.getLimit());
			search.setOffset(pageVo.getOffset());
			search.setTatal_list_count(totalCount);
			model.put("pageInfo", pageVo.getPagination());
		}
		
		List<HashMap> list = creditService.getSiteTranList(search);
		log.debug(""+list.size());
		model.put("list", list);
		
		return "admin/transaction";
	}
  
  
	@GetMapping("/gamelink")
	public String gamelink( HttpServletRequest request , ModelMap model, @ModelAttribute("searchVO") SiteSearch search) throws Exception {
		Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
		Site loginSite = (Site)authentication.getDetails();
		
		model.put("loginSite", loginSite);
		long siteCredit = siteService.getSiteCredit(loginSite.getSiteId());
		long underSiteCredit = siteService.getUnderSiteCredit(loginSite.getSiteId());
		long sitePoint = siteService.getSitePoint(loginSite.getSiteId());
		
		model.put("sitePoint", sitePoint);	
		model.put("siteCredit", siteCredit);	
		model.put("underSiteCredit", underSiteCredit);
		HashMap creditWait = siteService.getCreditWait(loginSite.getSiteIdx());
		
		model.put("creditWait", creditWait);	  
		long insureAmt = siteService.getInsureAmt(loginSite.getSiteId());
		long insurePointAmt = siteService.getInsurePointAmt(loginSite.getSiteId());	
		model.put("insureAmt", insureAmt);	  
		model.put("insurePointAmt", insurePointAmt);	 
		search.setSiteIdx(loginSite.getSiteIdx());
		
		List<HashMap> mylist = siteService.getSiteVendorList(search);
		List<HashMap> vendorlist = siteService.getVendorList(search);
		
		model.put("mylist", mylist);	  
		model.put("vendorlist", vendorlist);
		
		return "admin/gamelink";
	}
	
	@GetMapping("/venderlist")
	public String venderlist( HttpServletRequest request, ModelMap model, @ModelAttribute("searchVO") SiteSearch search) throws Exception {
		  Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
	    	Site loginSite = (Site)authentication.getDetails();
	    	model.put("loginSite", loginSite);
	    	
	    	search.setSiteIdx(loginSite.getSiteIdx());

		  return "admin/venderlist"; 
	}
  
	@GetMapping("/apiset")
	public String apiset( HttpServletRequest request , ModelMap model, @ModelAttribute("searchVO") SiteSearch search) throws Exception {
		Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
		Site loginSite = (Site)authentication.getDetails();
		model.put("loginSite", loginSite);
		
		long siteCredit = siteService.getSiteCredit(loginSite.getSiteId());
		long underSiteCredit = siteService.getUnderSiteCredit(loginSite.getSiteId());
		long sitePoint = siteService.getSitePoint(loginSite.getSiteId());
		
		model.put("sitePoint", sitePoint);	
		model.put("siteCredit", siteCredit);	
		model.put("underSiteCredit", underSiteCredit);
		
		long insureAmt = siteService.getInsureAmt(loginSite.getSiteId());
		long insurePointAmt = siteService.getInsurePointAmt(loginSite.getSiteId());	
		
		model.put("insureAmt", insureAmt);	  
		model.put("insurePointAmt", insurePointAmt);	 
		search.setSiteIdx(loginSite.getSiteIdx());
		
		return "admin/apiset";
	}


	@RequestMapping("/siteVenderUpdate")
	public @ResponseBody JSONObject  siteVenderUpdate( HttpServletRequest request, ModelMap model,  Vendor vendor) throws Exception {
		Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
		Site loginSite = (Site)authentication.getDetails();
		JSONObject obj = new JSONObject();
		
		vendor.setSiteIdx(loginSite.getSiteIdx());
		try {
			siteService.siteVenderUpdate(vendor);		 
			obj.put("RES", "SUCCESS");
		} catch(Exception e) {
			obj.put("RES", "FAIL");	
		}
		
		return obj;
	}
	
	
	@GetMapping("/parseOnOff")
	public @ResponseBody JSONObject parseOnOff(HttpServletRequest request, ModelMap model, @RequestParam("pStatus") String pStatus) throws Exception {
		JSONObject obj = new JSONObject();
		
		final String LOG_PREFIX = "#-Proc::parseOnOff:::";
		
		log.info(LOG_PREFIX + "전체 사이트 파싱설정::" + pStatus + "::START");
		
		String useYn = "";
		if("on".equals(pStatus)) {
			useYn = "Y";
		} else {
			useYn = "N";
		}
		log.info(LOG_PREFIX + "updateParseUseYN useYn::" + useYn);
		int result = siteService.updateParseUseYN(useYn);
		log.info(LOG_PREFIX + "updateParseUseYN result::" + result);
		
		log.info(LOG_PREFIX + "전체 사이트 파싱설정::" + pStatus + "::END");
		
		obj.put("RES", "SUCCESS");
		
		return obj;
	}
	
	
	private String makeApiKey(String param) {
		int n = 24; // n자리 쿠폰 
		char[] chs = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 
						'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 
						'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' ,'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z' };
		
		Random rd = new Random();
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < n; i++) {
			char ch = chs[rd.nextInt(chs.length)];
			sb.append(ch);
		}
		
		return sb.toString();
	}
}
