package com.bb.admin.controller;

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

import jakarta.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.annotation.Secured;
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.ResponseBody;

import com.bb.model.CommonParamAdmin;
import com.bb.model.Insure;
import com.bb.model.PageFormVO;
import com.bb.model.Site;
import com.bb.model.SiteSearch;
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 lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;

@Slf4j
@Controller
@RequestMapping(value = "/insurance")
@PreAuthorize("hasRole('ADMIN')")
public class InsuranceController {
	
	@Autowired
	SiteService siteService;
	
	@Autowired
	CreditService creditService;
	
	
	 @RequestMapping("/addProc")
     public @ResponseBody JSONObject  addProc( HttpServletRequest request, ModelMap model,  Insure insure) throws Exception {
		JSONObject obj = new JSONObject();
		Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
	    Site loginSite = (Site)authentication.getDetails();
		insure.setSiteId(loginSite.getSiteId());
		insure.setSiteIdx(loginSite.getSiteIdx());
		long siteCredit = siteService.getSiteCredit(loginSite.getSiteId());
		long sitePoint = siteService.getSitePoint(loginSite.getSiteId());
		long insureAmt = siteService.getInsureAmt(loginSite.getSiteId());
    	long insurePointAmt = siteService.getInsurePointAmt(loginSite.getSiteId());	
    	
    	
    	List<HashMap> vederRateList = siteService.getVenderRateList(loginSite);
    	if(vederRateList.size() <0) {
    		obj.put("RES", "FAIL");
    		obj.put("MSG", "보험설정을 해주세요.");
     		return obj;
    	}else{
    		
    		  System.out.println(":dddddddddd" + vederRateList.get(0).get("insureUpSiteIdx"));	
    		if(vederRateList.get(0).get("insureUpSiteIdx") == null || "null".equals(vederRateList.get(0).get("insureUpSiteIdx"))) {
    			
    			obj.put("RES", "FAIL");
        		obj.put("MSG", "보험적용컴퍼니가 없습니다. 보험설정을 해주세요.");
         		return obj;
    		}
    	}
    	
    	insure.setSiteIdx(loginSite.getSiteIdx());
    	insure.setSiteId(loginSite.getSiteId());
    	insure.setInsureUpSiteId(vederRateList.get(0).get("insureUpSiteId").toString());
    	insure.setInsureUpSiteIdx(Long.parseLong(vederRateList.get(0).get("insureUpSiteIdx").toString()));
    	insure.setPreCreditAmt(siteCredit);
    	insure.setPreCreditPoint(sitePoint);
    	insure.setPreInsureAmt(insureAmt);
    	insure.setPreInsurePoint(insurePointAmt);
    	insure.setStatus("0");
    	insure.setRegId(loginSite.getSiteId());
    
	    if("TRANIN".equals(insure.getInsureType())){ //충전 신청
	    
	    			
	    	
	    	
	    	
	    }else if("TRANOUT".equals(insure.getInsureType())){ //환전 신청
	    	
	    	
	    }
	    
     
          	
     	
     	  		      	
     	int res = creditService.insertInsure(insure);		 
	           
     	obj.put("RES", "SUCCESS");
     
 		return obj;
     }
	 
	 @RequestMapping("/updateStatus")
     public @ResponseBody JSONObject updateStatus( HttpServletRequest request, ModelMap model,  Insure insure) throws Exception {
		  
		Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
	    Site loginSite = (Site)authentication.getDetails();
		insure.setSiteId(loginSite.getSiteId());
		insure.setSiteIdx(loginSite.getSiteIdx());		 
	    // 상위 보험 관련 데이터 가져오기
		
	
     	JSONObject obj = new JSONObject();
          	     	     	  		      	
     	int res = creditService.updateInsureStatus(insure);		 
	           
     	obj.put("RES", "SUCCESS");
     
 		return obj;
     }
	  
	
	
	@GetMapping("/set")
    public String index( HttpServletRequest request ,  ModelMap model) throws Exception {
    	System.out.println("index");
    	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());
    	model.put("underSiteCredit", underSiteCredit);	
    	model.put("siteCredit", siteCredit);
    	long sitePoint = siteService.getSitePoint(loginSite.getSiteId());
    	model.put("sitePoint", sitePoint);	
    	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);	  
    	 
    	
    	//상위 컴파니 불려오기
    	
    	List<HashMap> flowList = siteService.getSiteFlow(loginSite);
    	model.put("flowList", flowList);	  
    	//벤더 리스트 rate 불러오기
    	List<HashMap> vederRateList = siteService.getVenderRateList(loginSite);
    	
    	int uppersiteIdx = 0;
    	if(vederRateList.size()>0) {
    		
    		try {
    		uppersiteIdx = Integer.parseInt(vederRateList.get(0).get("insureUpSiteIdx").toString());
    		}catch(Exception e) {
    			 uppersiteIdx = 0;
    			
    		}
    	}
    	model.put("uppersiteIdx", uppersiteIdx);	  
    	
    	/*SELECT * FROM vendors_info vi
    	LEFT JOIN `site_rate_info` sri ON vi.vendorIdx = sri.vendorIdx
    	 WHERE vi.delYn= 'N' AND vi.useYn ='Y'
    	 AND sri.siteIdx = 1
    	 */
    	model.put("vederRateList", vederRateList);	  
    	
    	return "admin/insuredSet";        
    }
	
	 @RequestMapping("/setSave")
     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", loginSite.getSiteIdx());
     		paramData.put("insureUpSiteIdX", commonParamAdmin.getParam().get("uppersiteIdx"));
     		log.info(paramData.toString());
     		
     		ObjectMapper mapper = new ObjectMapper();
			HashMap paramMap = mapper.readValue(paramData.toString(), new TypeReference<HashMap>() {});
     		
     		siteService.saveVendorInsureRate(paramMap);
     	}
     	
     	
     	
     	  		      	
     
	           
     	obj.put("RES", "SUCCESS");
     
 		return obj;
     }
	
	@GetMapping("/betList")
    public String betList( HttpServletRequest request ,ModelMap model ,  @ModelAttribute("searchVO") SiteSearch search) throws Exception {
    	System.out.println("index");
    	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());
    	model.put("underSiteCredit", underSiteCredit);	
    	model.put("siteCredit", siteCredit);
    	long sitePoint = siteService.getSitePoint(loginSite.getSiteId());
    	model.put("sitePoint", sitePoint);	
    	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("up".equals(search.getUpdown())){
    		search.setSiteIdx(loginSite.getSiteIdx());
    	}else if("down".equals(search.getUpdown())){
    		search.setUpperSiteId(loginSite.getSiteId());
    	}
    	search.setSearchType("BET");
    	search.setStatus("1");
					
		int totalCount = creditService.getInsureListCnt(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.getInsureList(search);
    	
    	model.put("list", list);	  
    	
    	return "admin/insuredBetList";        
    }
	
	@GetMapping("/history")
    public String history( HttpServletRequest request ,  ModelMap model) throws Exception {
    	System.out.println("index");
    	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());
    	model.put("underSiteCredit", underSiteCredit);	
    	model.put("siteCredit", siteCredit);
    	long sitePoint = siteService.getSitePoint(loginSite.getSiteId());
    	model.put("sitePoint", sitePoint);	
    	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/insuredHistory";        
    }
	
	@GetMapping("/apply")
    public String apply( HttpServletRequest request ,  ModelMap model, @ModelAttribute("searchVO") SiteSearch search) throws Exception {
    	System.out.println("index");
    	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());
    	model.put("underSiteCredit", underSiteCredit);	
    	model.put("siteCredit", siteCredit);
    	long sitePoint = siteService.getSitePoint(loginSite.getSiteId());
    	model.put("sitePoint", sitePoint);	
    	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.setUpperSiteId(loginSite.getSiteId());    
    	search.setSearchType("TRANIN");
    	
    	if(search.getStatus()==null || "".equals(search.getStatus())) {
    		search.setStatus("0");
    	}
    	
		
		int totalCount = creditService.getInsureListCnt(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());
		}
		
		model.put("searchVO", search);
		List<HashMap> list = creditService.getInsureList(search);
		model.put("list", list);
    	
		// model.addObject("long", Long.parseLong(null));
    	
    	
    	return "admin/insuredApply";        
    }
	
	
	
	
	
	@GetMapping("/exchange")
    public String exchange( HttpServletRequest request ,  ModelMap model, @ModelAttribute("searchVO") SiteSearch search) throws Exception {
		System.out.println("index");
    	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());
    	model.put("underSiteCredit", underSiteCredit);	
    	model.put("siteCredit", siteCredit);
    	long sitePoint = siteService.getSitePoint(loginSite.getSiteId());
    	model.put("sitePoint", sitePoint);	
    	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.setUpperSiteId(loginSite.getSiteId());    
    	search.setSearchType("TRANOUT");
    	
    	if(search.getStatus()==null || "".equals(search.getStatus())) {
    		search.setStatus("0");
    	}
    	
		
		int totalCount = creditService.getInsureListCnt(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());
		}
		
		model.put("searchVO", search);
		List<HashMap> list = creditService.getInsureList(search);
		model.put("list", list);
    	
		// model.addObject("long", Long.parseLong(null));  
    	 
    	
    	return "admin/insuredExchange";        
    }
	
	
}
