package kr.co.uplus.ez.api.channelMgt;

import kr.co.uplus.ez.api.channelMgt.dto.*;
import kr.co.uplus.ez.common.components.WebClientRequestService;
import kr.co.uplus.ez.common.data.ApiResponseCode;
import kr.co.uplus.ez.common.data.Const;
import kr.co.uplus.ez.common.data.Paging;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.mybatis.spring.SqlSessionTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class ChannelMgtService {

	private static final Logger logger = LoggerFactory.getLogger(ChannelMgtService.class);

	@Autowired
	@Qualifier("sqlSessionTemplateDb1")
	private SqlSessionTemplate sqlSessionMaster;

	@Autowired
	@Qualifier("sqlSessionTemplateDb2")
	private SqlSessionTemplate sqlSessionSlave;
	
	@Autowired
	WebClientRequestService clientRequestService;
	
	@Value("${hubeasy-api.domain:http://localhost:7070/}")
	String apiDomain;
	
	@Value("${hubeasy-api.url.alTolkTemplet:api/v1/kko/template/get}")
	String apiUrlAlTolkTemplet;

	/**
	 * date : 2022. 4. 25.
	 * auth : ckr
	 * desc : 알림톡 템플릿 목록 조회
	 * @param tmpltListReqDto
	 * @return
	 */
	public TmpltListResDto tmpltList(TmpltListReqDto tmpltListReqDto, String targetUserId) {
		ChannelMgtMapper channelMgtMapper = sqlSessionSlave.getMapper(ChannelMgtMapper.class);
		String nowPage = String.valueOf(tmpltListReqDto.getPage());

		tmpltListReqDto.setUserId(targetUserId);

		int totalCnt = channelMgtMapper.selectTmpltTotalCnt(tmpltListReqDto);

		if(totalCnt == 0) {
			Paging paging = new Paging();
			paging.setPage(nowPage);
			paging.setTotalCnt(String.valueOf(totalCnt));
			TmpltListRes tmpltListRes = new TmpltListRes();
			tmpltListRes.setList(new ArrayList<>());
			tmpltListRes.setPaging(paging);
			return new TmpltListResDto(ApiResponseCode.CM_NOT_FOUND, tmpltListRes);
		}
		logger.info("perPage : "+tmpltListReqDto.getPagePerRows());
		int page = tmpltListReqDto.getPage();
		int pagePerRows = tmpltListReqDto.getPagePerRows();
		page = (page -1) * pagePerRows;
		tmpltListReqDto.setPage(page);

		List<TmpltInfo> tmpltInfos =  channelMgtMapper.selectTmpltList(tmpltListReqDto);

		Paging paging = new Paging();
		paging.setPage(nowPage);
		paging.setTotalCnt(String.valueOf(totalCnt));

		TmpltListRes tmpltListRes = new TmpltListRes();
		tmpltListRes.setList(tmpltInfos);
		tmpltListRes.setPaging(paging);

		return new TmpltListResDto(ApiResponseCode.SUCCESS, tmpltListRes);
	}

	//
	public TmpltListExcelResDto tmpltListExcel(TmpltListExcelReqDto tmpltListExcelReqDto, String targetUserId) {
		ChannelMgtMapper channelMgtMapper = sqlSessionSlave.getMapper(ChannelMgtMapper.class);

		tmpltListExcelReqDto.setUserId(targetUserId);

		List<TmpltInfo> tmpltInfos =  channelMgtMapper.selectTmpltListExcel(tmpltListExcelReqDto);

		TmpltListRes tmpltListRes = new TmpltListRes();
		tmpltListRes.setList(tmpltInfos);

		return new TmpltListExcelResDto(ApiResponseCode.SUCCESS, tmpltListRes);
	}
	
	
	/**
	 * desc : 알림톡 템플릿 반려 목록 조회
	 * @param tmpltListReqDto
	 * @return
	 */
	@SuppressWarnings({ "unchecked", "null" })
	public TmpltListResDto tmpltRejectList(TmpltListReqDto tmpltListReqDto) {
		RjtTmpltListRes tmpltListRes = new RjtTmpltListRes();
		Map<Object, Object> apiResultMap = null;
		List<Map<Object,Object>> dataListMap = null;
		//List<Map<Object,Object>> dataTempListMap = null;
		List<Map<Object,Object>> rjtDataListMap = null;
		
		JSONObject jsonObject = new JSONObject();
		JSONArray array = new JSONArray();
		String callUrl = apiDomain + apiUrlAlTolkTemplet;
		
		try {
			jsonObject.put("senderKey", tmpltListReqDto.getSndrprofKey());
			jsonObject.put("templateKey", tmpltListReqDto.getTmpltKey());
			array.add(jsonObject);
			logger.info("array : {}", array);
			apiResultMap = (Map<Object, Object>) clientRequestService.callBySyncPost(callUrl, array);
			
			if("0000".equals(apiResultMap.get("retCode"))) {
				Map<Object, Object> dataMap = (Map<Object, Object>) apiResultMap.get("data");
				logger.info("dataMap : {}", dataMap);
				dataListMap = (List<Map<Object, Object>>) dataMap.get("list");
				Map<Object, Object> dataTempMap = dataListMap.get(0);
				if(dataTempMap.get("comments") != null && !"".equals(dataTempMap.get("comments"))) {
					rjtDataListMap = (List<Map<Object, Object>>) dataTempMap.get("comments");
					tmpltListRes.setList(rjtDataListMap);
				}
				return new TmpltListResDto(ApiResponseCode.SUCCESS, tmpltListRes);
			}else {
				return new TmpltListResDto(ApiResponseCode.CM_DB_QUERY_ERR);
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		return new TmpltListResDto(ApiResponseCode.SUCCESS, tmpltListRes);
	}
	
	
}
