package com.style24.front.biz.thirdparty;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.List;
import java.util.Arrays;

import javax.annotation.PostConstruct;

import com.gagaframework.web.parameter.GagaMap;
import com.style24.persistence.domain.searchengine.AutoCompleteResponse;
import com.style24.persistence.domain.searchengine.CateResponse;
import com.style24.persistence.domain.searchengine.Filter;
import com.style24.persistence.domain.searchengine.FilterResponse;
import com.style24.persistence.domain.searchengine.GoodsListResponse;
import com.style24.persistence.domain.searchengine.PlanningResponse;
import com.style24.persistence.domain.searchengine.SearchEngine;
import com.style24.persistence.domain.searchengine.FeedbackResponse;
import istyle.EventSearch;
import org.json.simple.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.Gson;
import com.style24.front.biz.dao.TsfDisplayDao;
import com.style24.persistence.domain.Cate1;

import istyle.AutoSearch;
import istyle.PlanSearch;
import istyle.SearchService;

import lombok.extern.slf4j.Slf4j;

/**
 * 검색엔진 - NHN다이퀘스트
 *
 * @author gagamel
 * @since 2021. 04. 29
 */
@Component
@Slf4j
public class SearchEngineDiquest {

	@Autowired
	private Environment env;

	private String ipAddr;	// 검색엔진 IP
	private Integer port;	// 검색엔진 포트

	@Autowired
	private TsfDisplayDao displayDao;

	@PostConstruct
	public void init() {
		ipAddr = env.getProperty("search.engine.diquest.ip");
		port = Integer.valueOf(env.getProperty("search.engine.diquest.port"));

		log.debug("\n\n---- NHN Diquest initialization started ----");
		log.debug("ipAddr: [{}]", ipAddr);
		log.debug("port: [{}]", port);
		log.debug("\n--- NHN Diquest initialization completed ----\n");
	}

	/**
	 * 인기검색어 조회
	 * @return
	 * @author gagamel
	 * @since 2021. 5. 10
	 */
	public SearchEngine getTrendKeywordList() {
		SearchEngine result = new SearchEngine();

		// 인기검색어
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("adminIp", ipAddr);
		paramMap.put("adminPort", port);
		//log.info("///[getTrendKeywordList] paramMap: {}", paramMap);

		try {
			JSONObject jsonObj = AutoSearch.trendKeyword(paramMap);
			//log.info("///[getTrendKeywordList] jsonObj: {}", jsonObj.toJSONString());

			Gson gson = new Gson();
			result = gson.fromJson(jsonObj.toJSONString(), SearchEngine.class);
			//log.info("///[getTrendKeywordList] result: {}", result);
		} catch (Exception e) {
			e.printStackTrace();
		}

		return result;
	}

	/**
	 * 자동완성 조회
	 * @param keyword - 검색어
	 * @return
	 * @author gagamel
	 * @since 2021. 6. 7
	 */
	public AutoCompleteResponse getAutoComplete(String keyword) {
		AutoCompleteResponse result = new AutoCompleteResponse();

		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("adminIp", ipAddr);
		paramMap.put("adminPort", port);
		paramMap.put("keyword", keyword);
		//log.info("///[getAutoComplete] paramMap: {}", paramMap);

		try {
			JSONObject jsonObj = new JSONObject();
			jsonObj = AutoSearch.getAutoComplete(paramMap);
			
			//log.info("///[getAutoComplete] jsonObj: {}", jsonObj.toJSONString());

			Gson gson = new Gson();
			result = gson.fromJson(jsonObj.toJSONString(), AutoCompleteResponse.class);
			//log.info("///[getAutoComplete] result: {}", result);
		} catch (Exception e) {
			//e.printStackTrace();
		}

		return result;
	}

	/**
	 * 카테고리 목록
	 * @param params - 파라미터
	 * @return
	 * @author gagamel
	 * @since 2021. 5. 31
	 */
	public Collection<Cate1> getCategoryList(SearchEngine params) {
		Collection<Cate1> result = new ArrayList<Cate1>();

		Map<String, Object> paramMap = this.convertObjectToMap(params);
		paramMap.put("adminIp", ipAddr);
		paramMap.put("adminPort", port);
//		paramMap.put("cate1No", 1300);
//		paramMap.put("brandGroupNo", 0);
//		paramMap.put("keyword", "키즈");
//		paramMap.put("formalGb", "G009_20");

		// 브랜드그룹번호 값이 있으면 (=브랜드메인에서 조회했으면)
		paramMap.put("defaultCateYn", "Y");
		if (params.getBrandGroupNo() > 0) {
			paramMap.put("defaultCateYn", displayDao.getBrandGroupDefaultCategoryYn(params.getBrandGroupNo()));
		}
		//log.info("///[getCategoryList] paramMap: {}", paramMap);

		try {
			JSONObject jsonObj = SearchService.getCategoryGoodsList(paramMap);
			//log.info("///[getCategoryList] jsonObj: {}", jsonObj.toJSONString());

			Gson gson = new Gson();
			CateResponse response = gson.fromJson(jsonObj.toJSONString(), CateResponse.class);

			if (jsonObj.get("returnCode").toString().equals("1")) { // 성공
				result = response.getResponse();
				//log.info("///[getCategoryList] result: {}", result);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		return result;
	}

	/**
	 * 필터 목록
	 * @param params - 파라미터
	 * @return
	 * @author gagamel
	 * @since 2021. 5. 31
	 */
	public Collection<Filter> getFilterList(SearchEngine params) {
		Collection<Filter> result = new ArrayList<Filter>();

		Map<String, Object> paramMap = this.convertObjectToMap(params);
		paramMap.put("adminIp", ipAddr);
		paramMap.put("adminPort", port);
		//log.info("///[getFilterList] paramMap: {}", paramMap);

		try {
			JSONObject jsonObj = SearchService.getFilterList(paramMap);
			//log.info("///[getFilterList] jsonObj: {}", jsonObj.toJSONString());

			Gson gson = new Gson();
			FilterResponse response = gson.fromJson(jsonObj.toJSONString(), FilterResponse.class);

			if (jsonObj.get("returnCode").toString().equals("1")) { // 성공
				result = response.getResponse();
				//log.info("///[getFilterList] result: {}", result);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		return result;
	}

	/**
	 * 상품리스트
	 * @param params - 파라미터
	 * @return
	 * @author gagamel
	 * @since 2021. 5. 31
	 */
	public GoodsListResponse getGoodsList(SearchEngine params) {
		GoodsListResponse result = new GoodsListResponse();

		Map<String, Object> paramMap = this.convertObjectToMap(params);
		paramMap.put("adminIp", ipAddr);
		paramMap.put("adminPort", port);
		paramMap.put("pageNumber", String.valueOf(params.getPageNo()));
		paramMap.put("rowsPerPage", String.valueOf(params.getPageSize()));
		//log.info("///[getGoodsList] paramMap: {}", paramMap);

		try {
			
			JSONObject jsonObj = SearchService.getGoodsList(paramMap);
			//log.info("///[getGoodsList] jsonObj: {}", jsonObj.toJSONString());

			if (jsonObj.get("returnCode").toString().equals("1")) { // 성공
				Gson gson = new Gson();
				result = gson.fromJson(jsonObj.toJSONString(), GoodsListResponse.class);
				//log.info("///[getGoodsList] result: {}", result);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		return result;
	}

	private String[] getStringArray (String[] arr){
		String[] arry = null;
		if(arr != null){
			List<String> lst = new ArrayList<String>(Arrays.asList(arr));
			arry = lst.toArray(new String[lst.size()]);
		}
		return arry;
	}

	/**
	 * 기획전 목록
	 * @param keyword - 검색어
	 * @param pageNo - 페이지번호
	 * @param pageSize - 페이지사이즈
	 * @return
	 * @author gagamel
	 * @since 2021. 6. 7
	 */
	public PlanningResponse getPlanningList(String keyword, int pageNo, int pageSize) {
		PlanningResponse result = new PlanningResponse();

		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("adminIp", ipAddr);
		paramMap.put("adminPort", port);
		paramMap.put("keyword", keyword);
		paramMap.put("pageNumber", String.valueOf(pageNo));
		paramMap.put("rowsPerPage", String.valueOf(pageSize));
		//log.info("///[getPlanningList] paramMap: {}", paramMap);

		try {
			JSONObject jsonObj = PlanSearch.planSearchApi(paramMap);
			//log.info("///[getPlanningList] jsonObj: {}", jsonObj.toJSONString());

			Gson gson = new Gson();
			result = gson.fromJson(jsonObj.toJSONString(), PlanningResponse.class);
			//log.info("///[getPlanningList] result: {}", result);
		} catch (Exception e) {
			e.printStackTrace();
		}

		return result;
	}

	/**
	 * 이벤트 목록
	 * @param keyword - 검색어
	 * @param pageNo - 페이지번호
	 * @param pageSize - 페이지사이즈
	 * @return
	 * @author gagamel
	 * @since 2021. 6. 7
	 */
	public PlanningResponse getEventList(String keyword, int pageNo, int pageSize) {
		PlanningResponse result = new PlanningResponse();

		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("adminIp", ipAddr);
		paramMap.put("adminPort", port);
		paramMap.put("keyword", keyword);
		paramMap.put("pageNumber", String.valueOf(pageNo));
		paramMap.put("rowsPerPage", String.valueOf(pageSize));
		//log.info("///[getEventList] paramMap: {}", paramMap);

		try {
			JSONObject jsonObj = EventSearch.eventSearchApi(paramMap);
			//log.info("///[getEventList] jsonObj: {}", jsonObj.toJSONString());

			Gson gson = new Gson();
			result = gson.fromJson(jsonObj.toJSONString(), PlanningResponse.class);
			//log.info("///[getEventList] result: {}", result);
		} catch (Exception e) {
			e.printStackTrace();
		}

		return result;
	}

	/**
	 * Object를 Map으로 변환
	 * @param obj - Object
	 * @return
	 */
	@SuppressWarnings("unchecked")
	private Map<String, Object> convertObjectToMap(Object obj) {
		ObjectMapper objectMapper = new ObjectMapper();
		return objectMapper.convertValue(obj, Map.class);
	}

	/**
	 * 연관검색어
	 * @param keyword - 검색어
	 * @return
	 * @author bin2107
	 * @since 2021. 7. 20
	 */
	public FeedbackResponse sendFeedbackLog(String keyword, String searchId){
		FeedbackResponse result = new FeedbackResponse();
		//log.info("///[getFeedbackLog] keyword: {}", keyword);
		//log.info("///[getFeedbackLog] dq_id: {}", searchId);
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("adminIp", ipAddr);
		paramMap.put("adminPort", port);
		paramMap.put("keyword", keyword);
		paramMap.put("dq_id", searchId);
		//log.info("///[getFeedbackLog] paramMap: {}", paramMap);

		try {
			int feedbackLog = SearchService.feedbackLog(paramMap);
			//log.info("///[getFeedbackLog] returnCode : {}", feedbackLog);
			result.setReturnCode(feedbackLog);
			//log.info("///[getFeedbackLog] result: {}", result);
		} catch (Exception e) {
			e.printStackTrace();
		}

		return result;
	}

}
